一、背景
在業(yè)務(wù)開發(fā)的時(shí)候,由于MyBatis框架的insert語句默認(rèn)是不返回記錄的主鍵值,而是返回插入的記錄條數(shù)的,但是如果業(yè)務(wù)層需要得到插入數(shù)據(jù)的主鍵時(shí)候,可以通過配置的方式來實(shí)現(xiàn)獲取插入數(shù)據(jù)的ID功能。
二、如何解決
方法1、開啟useGeneratedKeys屬性方法
<!--
useGeneratedKeys="true" 開啟新增主鍵返回功能
keyProperty="id" user實(shí)體主鍵屬性
keyColumn="id" user表中主鍵列
-->
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into user(username,password) values (#{username},#{password})
</insert>
方法2、使用<selectKey>和 order="AFTER"方式
<!--
keyColumn="id" user表中主鍵列
keyProperty="id" user實(shí)體主鍵屬性
resultType="int" user實(shí)體主鍵屬性類型
order="AFTER" 表示此標(biāo)簽內(nèi)部sql語句在insert執(zhí)行之前(執(zhí)行),還是之后執(zhí)行(執(zhí)行)
AFTER 之后執(zhí)行【在自增主鍵時(shí)】
BEFORE 之前執(zhí)行【使用指定主鍵時(shí)】
-->
<insert id="insertUser" parameterType="User" >
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user(username,password) values(#{username},#{password})
</insert>
三、Java調(diào)用
在java中調(diào)用時(shí)候,怎么拿到自增主鍵?
錯(cuò)誤拿?。?/p>
int i = tableDataMapper.insertMaster(masterSQL);
System.out.println("主鍵:"+i); //返回的依舊是 0 或者 1 ,代表執(zhí)行成功或失敗
正確拿?。?/p>
tableDataMapper.insertMaster(masterSQL);
System.out.println("主鍵:"+masterSQL.getId()); //因?yàn)樯厦嬲f了,mybatis會(huì)把自增id封裝在你的入?yún)ean的指定字段中,所以應(yīng)該從 入?yún)?get(指定字段) 去獲取
四、注意
1、這兩種方式都僅支持主鍵自增類型的數(shù)據(jù)庫 MySQL 和 SqlServer,Oracle不支持,并且設(shè)置的ID是自增類型的才行;文章來源:http://www.zghlxwxcb.cn/news/detail-503498.html
2、如果使用INSERT一條語句插入多行數(shù)據(jù)時(shí), LAST_INSERT_ID() 只會(huì)返回插入的第一行數(shù)據(jù)時(shí)產(chǎn)生的值。比如我使用INSERT一次插入了 4 條數(shù)據(jù),它們的 id 分別是 1,2,3,4,那么最后返回的ID還是 1 這個(gè)值。文章來源地址http://www.zghlxwxcb.cn/news/detail-503498.html
到了這里,關(guān)于【SpringBoot】Mybatis執(zhí)行insert/update后如何獲得主鍵id的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!