您的当前位置:首页mybatis注解获取插入的自增主键id
mybatis注解获取插入的自增主键id
来源:锐游网
@Insert("<script>insert into user_cert(identity_no,name,auth_time,age,applet_id <if test='userAuthenticationRequestV3.phone1 !=null '> ,telephone</if><if test='userAuthenticationRequestV3.addr !=null '> ,address</if>)" +
"VALUES(#{userAuthenticationRequestV3.ocrCardNo},#{userAuthenticationRequestV3.ocrName},NOW(),#{age},#{userAuthenticationRequestV3.applet_id}<if test='userAuthenticationRequestV3.phone1 !=null ' > ,#{userAuthenticationRequestV3.phone1}</if><if test='userAuthenticationRequestV3.addr !=null '> ,#{userAuthenticationRequestV3.addr}</if>)</script>")
@SelectKey(statement="select last_insert_id()", keyProperty="userAuthenticationRequestV3.cerid", before=false, resultType=int.class)
下面介绍一个重要注解@SelctKey(statement=“SQL语句”,keyProperty=“将SQL语句查询结果存放到keyProperty中去”,before=“true表示先查询再插入,false反之”,resultType=int.class)
其中:
statement是要运行的SQL语句,它的返回值通过resultType来指定
before表示查询语句statement运行的时机
keyProperty表示查询结果赋值给代码中的哪个对象,keyColumn表示将查询结果赋值给数据库表中哪一列
keyProperty和keyColumn都不是必需的,有没有都可以
before=true,插入之前进行查询,可以将查询结果赋给keyProperty和keyColumn,赋给keyColumn相当于更改数据库
befaore=false,先插入,再查询,这时只能将结果赋给keyProperty
赋值给keyProperty用来“读”数据库,赋值给keyColumn用来写数据库
selectKey的两大作用:1、生成主键;2、获取刚刚插入数据的主键。
使用selectKey,并且使用MySQL的last_insert_id()函数时,before必为false,也就是说必须先插入然后执行last_insert_id()才能获得刚刚插入数据的ID。
注意:
@SelectKey查询的结果也就是keyProperty 的值将会存放在userAuthenticationRequestV3 的cerid 这个属性中,所以传参中必须要一个实体类,不然主键值不知道放在哪里
因篇幅问题不能全部显示,请点此查看更多更全内容