MyBatis+MySQL 返回插入的主鍵ID

來源:互聯網
上載者:User

標籤:

需求:使用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


MyBatis+MySQL 返回插入的主鍵ID

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.