Java MyBatis 插入数据库返回主键

实现有两种方式:

方式一:使用keyProperty属性
mapper.xml中:
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="Id" parameterType="com.chenzhou.mybatis.User">
    insert into user(userName,password,comment)
    values(#{userName},#{password},#{comment})
</insert>

  

useGeneratedKeys="true" 表示给主键设置自增长
keyProperty="Id"  表示将自增长后的Id赋值给实体类中的Id字段。
parameterType="com.chenzhou.mybatis.User" 这个属性指向传递的参数实体类
实体类中Id 要有getter() and setter()方法,底层是通过调用getter()、setter()方法来实现的。

由于我在MySQL数据库中建表时候已经设置了字段自增长,故最终我选择了第二种方式。

方式二:

使用<selectKey>标签:
   <!-- 插入一个商品 -->
    <insert id="insertProduct" parameterType="domain.model.ProductBean" >
       <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="Id">
          SELECT LAST_INSERT_ID()
      </selectKey>
        INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId});
    </insert>

  

<insert></insert> 中没有resultType属性,但是<selectKey></selectKey> 标签是有的。
order="AFTER" 表示先执行插入语句,之后再执行查询语句。
可被设置为 BEFORE 或 AFTER。
如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。
如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素-这和如 Oracle 数据库相似,可以在插入语句中嵌入序列调用
keyProperty="Id"  表示将自增长后的Id赋值给实体类中的Id字段。
SELECT LAST_INSERT_ID() 表示MySQL语法中查询出刚刚插入的记录自增长Id.
实体类中Id 要有getter() and setter(); 方法


参考文档: https://www.cnblogs.com/xingyunblog/p/6243179.html



原文地址:https://www.cnblogs.com/quan-coder/p/8340618.html