一、使用JDBC方式返回主鍵id
在MyBatis中,我們可以通過使用keyProperty和useGeneratedKeys屬性實現在執行插入操作時返回主鍵id。但是,這種方式適用於支持JDBC 3.0或更高版本,並且我們必須使用支持自動鍵生成的數據庫。
<insert id="insertUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user (username, password, phone) values (#{username}, #{password}, #{phone})
</insert>
上述示例代碼中,我們通過keyProperty=”id”指定了返回id值,並且useGeneratedKeys=”true”告訴MyBatis使用自動生成的主鍵值。
二、使用Mapper接口方法返回主鍵id
除了使用JDBC方式返回主鍵id,我們還可以通過Mapper接口方法實現。具體做法是在Mapper接口中定義一個返回主鍵id的方法,並在對應的XML映射文件中實現該方法。
例如,我們可以在UserMapper接口中定義以下方法:
int addUser(User user);
在XML映射文件中,我們可以使用selectKey元素實現返回主鍵id。如下所示:
<insert id="addUser" parameterType="User">
insert into user (username, password, phone) values
(#{username}, #{password}, #{phone})
<selectKey keyProperty="id" order="AFTER" resultType="Long">
select LAST_INSERT_ID()
</selectKey>
</insert>
上述示例代碼中,我們在插入操作完成後,使用<selectKey>元素獲取插入的主鍵值,並將其賦值給keyProperty=”id”指定的屬性。
三、使用@Options註解返回主鍵id
在MyBatis 3.4.2及以後的版本中,我們還可以使用@Options註解實現返回主鍵id。具體做法是在Mapper接口方法上添加@Options註解,並指定對應屬性值即可。
例如,在UserMapper接口中,我們可以添加以下注解:
@Insert("insert into user (username, password, phone) values (#{username}, #{password}, #{phone})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int addUser(User user);
上述示例代碼中,我們使用@Options註解指定useGeneratedKeys = true告訴MyBatis使用自動生成的主鍵值,並指定keyProperty和keyColumn屬性分別指定返回主鍵值的屬性和數據庫表中主鍵id的列名。
四、小結
以上是在MyBatis中正確返回主鍵id的三種常用方法。我們可以根據實際情況選擇合適的方式,並通過合理的配置來提高代碼的可維護性和可讀性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/237960.html