MyBatis + MySQL returns the inserted primary key ID, mybatismysql

Source: Internet
Author: User

MyBatis + MySQL returns the inserted primary key ID, mybatismysql

Requirement: after a record is inserted into the MySQL database using MyBatis, the auto-increment primary key value of the record needs to be returned.

Method: Specify the keyProperty in mapper, for example:

1 <insert id = "insert" useGeneratedKeys = "true" keyProperty = "id" parameterType = "com. koala. blog. model. test "> 2 insert into test (id, name) 3 values (# {id, jdbcType = INTEGER}, # {name, jdbcType = VARCHAR}) 4 </insert>

As shown above, keyProperty = "id" is specified in insert, where id represents the primary key attribute of the inserted Test object.

You must also specify useGeneratedKeys = "true", otherwise it will not work.

Model and dao are automatically generated by mybatis generator.

How to use unit test:

1 @ Test2 public void testInsert () {3 com. koala. blog. model. test test = new com. koala. blog. model. test (); 4 test. setName ("haha"); 5 int result = testService. insert (test); // result indicates how many records are inserted. 6 LOGGER.info (test. getId (); // test. getId () is the primary key for getting new records. 7}

This method is applicable to auto-incrementing primary keys whose primary keys are int type.

You must set a primary key for a non-auto-increment primary key to insert data correctly. Therefore, useGeneratedKeys = "true" keyProperty = "id" is not configured"

You can obtain test. getId () correctly ()

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.