表结构:
/*==============================================================*/
/* Table: Dic_City */
/*==============================================================*/
create
table
Dic_City (
ID
int
identity
,
City_Code
varchar(
10)
not
null
,
Provinces_Code
varchar(
20)
not
null
,
State_Code
varchar(
10)
not
null
,
City_Name
varchar(
50)
null
,
PY_Code
varchar(
50)
null
,
PY_Code_Short
varchar(
10)
null
,
Ext1
varchar(
20)
null
,
Ext2
varchar(
20)
null
,
Ext3
varchar(
20)
null
,
Ext4
varchar(
20)
null
,
Ext5
varchar(
20)
null
,
constraint
PK_DIC_CITY
primary
key (
ID)
)
MyBatisXML配置,下面两种方式都行
方式1:
<insert
id=
"insert"
parameterType=
"cn.softsea.model.DicCity"
>
<selectKey
resultType=
"java.lang.Integer"
keyProperty=
"id"
order=
"AFTER"
>
SELECT @@IDENTITY
</selectKey>
insert into Dic_City (City_Code, Provinces_Code,
State_Code, City_Name, PY_Code,
PY_Code_Short, Ext1, Ext2,
Ext3, Ext4, Ext5)
values (#{cityCode,jdbcType=VARCHAR}, #{provincesCode,jdbcType=VARCHAR},
#{stateCode,jdbcType=VARCHAR}, #{cityName,jdbcType=VARCHAR}, #{pyCode,jdbcType=VARCHAR},
#{pyCodeShort,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR},
#{ext3,jdbcType=VARCHAR}, #{ext4,jdbcType=VARCHAR}, #{ext5,jdbcType=VARCHAR})
</insert>
方式2:
<insert
id=
"insert"
parameterType=
"cn.softsea.model.DicCity"
useGeneratedKeys=
"true"
keyProperty=
"id"
>
insert into Dic_City (City_Code, Provinces_Code,
State_Code, City_Name, PY_Code,
PY_Code_Short, Ext1, Ext2,
Ext3, Ext4, Ext5)
values (#{cityCode,jdbcType=VARCHAR}, #{provincesCode,jdbcType=VARCHAR},
#{stateCode,jdbcType=VARCHAR}, #{cityName,jdbcType=VARCHAR}, #{pyCode,jdbcType=VARCHAR},
#{pyCodeShort,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR},
#{ext3,jdbcType=VARCHAR}, #{ext4,jdbcType=VARCHAR}, #{ext5,jdbcType=VARCHAR})
</insert>
调用Mapper返回主键:
//生成新对象用于插入
DicCity
city
=
new
DicCity();
city
.
setCityCode(
"330100");
city
.
setCityName(
"杭州市");
//获取mapper对象
DicCityMapper cityMapper = (DicCityMapper) SpringContextUtil.getBean("dicCityMapper");
int row = cityMapper.insert(city); //insrt不再返回主键,只返回响应行数,这点和ibatis不同了
System.out.println("响应的行数:"+row);
//取得自增的标识列 ID的值
System.out.println("新插入的数据的ID:"+city.getId());