Mybatis+mysql returns the inserted primary key ID

Source: Internet
Author: User

Requirement: After you insert a record into the MySQL database using MyBatis, you need to return the self-increment primary key value for that record.

Method: Specify the Keyproperty property in Mapper, as shown in the following example:

<insert id= "Insertandgetid" usegeneratedkeys= "true" keyproperty= "UserId" parametertype= " Com.chenzhou.mybatis.User ">insert into User (username,password,comment) VALUES (#{username},#{password},#{ Comment}) </insert>

As shown above, we specified the keyproperty= "userid" in Insert, where the UserID represents the primary key attribute of the inserted user object.

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);}

Test:

User user = new user (), User.setusername ("Chenzhou"), User.setpassword ("xxxx"), user.setcomment ("Test insert data Return primary key function"); SYSTEM.OUT.PRINTLN ("PRIMARY key before insertion is:" +user.getuserid ()); Userdao.insertandgetid (user);//insert Operation SYSTEM.OUT.PRINTLN ("Insert main key to:" +user.getuserid ());

Output:

Before inserting the primary key is: 0 Insert the main key is: 15

Querying the database:

As shown above, the record that you just inserted has a primary key ID of 15


Mybatis+mysql returns the inserted primary key ID

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.