MyBatis is used to obtain the auto-generated primary key Id and instance code.

Source: Internet
Author: User

MyBatis is used to obtain the auto-generated primary key Id and instance code.

MyBatis obtains the auto-generated primary key Id and instance code.

When using a MySQL database, we generally use the auto-incrementing primary key of the database to automatically generate a primary key. If we need to insert data from the table at the same time when inserting the primary table, we usually need to know the primary key Id value automatically generated when inserting the primary table.

The following describes how to obtain the self-generated primary key of the database during MyBatis insertion:

1. XML configuration file

<Insert id = "insert" parameterType = "Person" useGeneratedKeys = "true" keyProperty = "id"> insert into person (name, pswd) values (# {name }, # {pswd}) </insert>

2. Mapper Methods

Int insert (Person person );

Note that when calling this method, the returned int value is not the primary key, but the number of records inserted. The primary key id is assigned to the input person object and is automatically assigned to the id attribute of the person object. For example:

Person person = new Person ("name", "psw"); // num indicates the number of records inserted. int num = PersonMapper. insert (person); // The id attribute of the person object is changed to the self-generated idint id = person. getId ();

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.