mybatis insert返回主键(sqlserver2008)
MyBatisXML配置,下面两种方式都行
方式1:
<insert id="insert" parameterType="com.user.model.User" >
<selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
SELECT @@IDENTITY
</selectKey>
<![CDATA[
insert into
tb_user(username,password) values(#{userName},#{password})
]]>
</insert>
方式2:
<insert id="insertUser" parameterType="com.user.model.User" useGeneratedKeys="true" keyProperty="id">
<![CDATA[
insert into
tb_user(username,password) values(#{userName},#{password})
]]>
</insert>
定义dao层、service层的insert方法
Action中调用
User user = new User();
user.setUserName("tom");
user.setPassword("123456");
int row = userService.insert(user); //注意:mybatis中insrt不再返回主键,只返回响应行数,这点和ibatis不同了
System.out.println("响应的行数:"+row);
int id = user.getId(); //从对象中取得自增的标识列ID的值
System.out.println("新插入的数据的ID:"+id);
MyBatis insert返回主键(sqlserver2008)