MyBatis insert插入数据返回主键

方法一

<insert id="insertGetId" useGeneratedKeys="true" keyProperty="id" parameterType="cn.com.xxx.mybatis.User">
    insert into user(userName,password,sex)
    values(#{userName},#{password},#{sex})
</insert>

useGeneratedKeys="true" 表示给主键设置自增长
keyProperty="id"  表示将自增长后的Id赋值给实体类中的id字段。
parameterType="cn.com.xxx.mybatis.User" 这个属性指向传递的参数实体类

方法二

    <insert id="id" parameterType="cn.com.xxx.mybatis.User" >
       <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
          SELECT LAST_INSERT_ID()
      </selectKey>

    insert into user(userName,password,sex)
    values(#{userName},#{password},#{sex})
</insert>

order="AFTER" 表示先执行插入语句,之后再执行查询语句。
可被设置为 BEFORE 或 AFTER。
如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。

SELECT LAST_INSERT_ID() 表示MySQL语法中查询出刚刚插入的记录自增长Id.

注:代码中取id是直接从insert的那个实体user.getId()获取。

猜你喜欢

转载自blog.csdn.net/lin252552/article/details/86552425
今日推荐