MyBatis insert 返回主键的方法

数据库:SqlServer2005

表结构:
/*==============================================================*/
/* Table: Dic_City */
/*==============================================================*/
create tableDic_City(
IDint identity,
City_Codevarchar( 10) not null,
Provinces_Codevarchar( 20) not null,
State_Codevarchar( 10) not null,
City_Namevarchar( 50) null,
PY_Codevarchar( 50) null,
PY_Code_Shortvarchar( 10) null,
Ext1varchar( 20) null,
Ext2varchar( 20) null,
Ext3varchar( 20) null,
Ext4varchar( 20) null,
Ext5varchar( 20) null,
constraintPK_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返回主键:
//生成新对象用于插入
DicCitycity= newDicCity();
city. setCityCode( "330100");
city. setCityName( "杭州市");

//获取mapper对象
DicCityMappercityMapper=(DicCityMapper)SpringContextUtil.getBean("dicCityMapper");

introw=cityMapper.insert(city);//insrt不再返回主键,只返回响应行数,这点和ibatis不同了

System.out.println("响应的行数:"+row);
//取得自增的标识列 ID的值
System.out.println("新插入的数据的ID:"+city.getId());

====================

如果使用mybatis.generator来生成DAO层的话,generatorConfig.xml中要使用:

<generatedKeycolumn="id"sqlStatement="MySql"identity="true"/>

你可能感兴趣的:(mybatis)