返回主键的三种种方式:
1:SET NOCOUNT ON SELECT @@IDENTITY AS ID
<insert id="insert" parameterType="com.montnets.luoy.entity.User" >
<selectKey resultType="java.lang.Integer" keyProperty="id" order="AFTER" >
SET NOCOUNT ON SELECT @@IDENTITY AS ID
</selectKey>
insert into tb_user (username, password, sex, email, age)
values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{sex,jdbcType=TINYINT},
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
</insert>
2:SELECT SCOPE_IDENTITY()
<insert id="insert" parameterType="com.montnets.luoy.entity.User" >
<selectKey resultType="java.lang.Integer" keyProperty="id" >
insert into tb_user (username, password, sex, email, age)
values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{sex,jdbcType=TINYINT},
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
SELECT SCOPE_IDENTITY()
</selectKey>
</insert>
注意:insert语句必须写到<selectKey>标签里面,不然获取不到主键值,返回空值null。
3:配置:useGeneratedKeys="true" keyProperty="id"
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.montnets.luoy.entity.User">
insert into tb_user (username, password, sex, email, age)
values (#{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{sex,jdbcType=TINYINT},
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
</insert>
注意:这种方式需要数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server) 。首先推荐使用这种方式。
通过以上三种方式,mybatis会自动把主键值存入传过来的参数User对象里面。在后台就可以用get方法获取id了。如下所示:
int rows = userDao.insert(user); //调用insert接口,返回影响的记录总数
int id = user.getId(); //得到主键值