MyBatis returns the primary key of the inserted record

Source: Internet
Author: User

If you want to insert a record and do something else immediately, you need to get the primary key (usually the ID) of the record, and the MyBatis is handled in the following way.

The DAO layer interface is defined as follows:

void Importuser (@Param ("user") user user);

Note: this cannot be caused by a string or int that defines the return value of the interface to return the primary key.

XML configuration file:

 <  Span style= "color: #800000;" >insert  id  = "Importuser"   Usegeneratedkeys  = "true"   Keyproperty  = "User.ID"  parametertype  = "Com.ywlaker.model.User"  >   INSERT into user (user_name) VALUES (#{user.username,jdbctype=varchar})  </ Span style= "color: #800000;" >insert  >   

Usegeneratedkeys = "true" means return primary key

keyproperty= "user.id" indicates that the primary key is received with the ID property of the parameter user object

This method executes the primary key of the new record, inserts the user object, and wants to return a primary key that can be defined at the previous level

@Override  Public throws serviceexception {  try  {This}  .    Usermapper.importuser (user);  returncatch  (Exception e) {  throwNew Serviceexception ("Database Error!  " ); }}

Of course, it is also possible to return directly to the user object.

MyBatis returns the primary key of the inserted record

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.