MyBatis如何在插入数据时获取数据库自增值
方式一:
使用useGenerateKey="true"
<insert id="save" useGenerateKey="true">
insert into tb_brand .......
</insert>
用useGenerateKeys="true"
后,不用再在写一句关于select的SQL(降低数据库的压力)而直接能够得到刚刚插进去的那个主键,需要注意的是这个属性只能用在主键能自增长的数据库,比如MySQL。
方式二:
使用<selectKey keyProperty="id">
获取数据库中最后插入的id并返回
<insert id="save">
<selectKey keyProperty="id">
select last_insert_id()
</selectKey>
insert into tb_brand .......
</insert>
拓展:
注意:MyBatisPlus在insert方法执行之后自动获取数据库自增id并赋值给对象
说明MyBatisPlus底层已经封装了类似上面方式1or方式2的代码实现数据库获取自增值。
Memorial Day is 522 days |