需求:使用MyBatis往MySQL數據庫中插入一條記錄后,需要返回該條記錄的自增主鍵值。
?
方法:在mapper中指定keyProperty屬性,示例如下:
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
</insert>
?如上所示,我們在insert中指定了keyProperty="userId",其中userId代表插入的User對象的主鍵屬性。
?
User.java
public class User {
private int userId;
private String userName;
private String password;
private String comment;
//setter and getter
}
?UserDao.java
public interface UserDao {
public int insertAndGetId(User user);
}
?測試:
User user = new User();
user.setUserName("chenzhou");
user.setPassword("xxxx");
user.setComment("測試插入數據返回主鍵功能");
System.out.println("插入前主鍵為:"+user.getUserId());
userDao.insertAndGetId(user);//插入操作
System.out.println("插入后主鍵為:"+user.getUserId());
?輸出:
插入前主鍵為:0
插入后主鍵為:15
?查詢數據庫:
?
如上所示,剛剛插入的記錄主鍵id為15
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

