1、useGeneratedKeys+keyProperty实现主键自增
这种方式是我们经常用到的方式,如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置为目标属性就 OK 了。
eg:
<insert id="insert" parameterType="im.ziwo.audit.baseservice.model.Attachment" useGeneratedKeys="true" keyProperty="id">
insert into attachment( <include refid="table_columns" /> )
values ( <include refid="entity_properties" /> )
</insert>
2、selectkey 方式主键自增
对于不支持自动生成主键列的数据库和可能不支持自动生成主键的 JDBC 驱动,比如oracle数据库,MyBatis 有另外一种方法来生成主键。
<insert id="insertSelective" parameterType="com.lepu.business.coupon.module.templet.entity.CouponTemplet">
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into coupon_templet......
属性解释:
resultType:结果的类型。通常 MyBatis 可以推断出来,但是为了更加准确,写上也不会有什么问题。
order:可以设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它首先会生成主键,设置 keyProperty 再执行插入语句。如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 中的语句 - 这和 Oracle 数据库的行为相似,在插入语句内部可能有嵌入索引调用。
SELECT LAST_INSERT_ID(),主键ID
3、参考
官网:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html
博客:https://blog.youkuaiyun.com/czd3355/article/details/71302441

451

被折叠的 条评论
为什么被折叠?



