Database discussion (i) MyBatis gets the id__ database for the current insert record

Source: Internet
Author: User

Issue: MyBatis will automatically generate an Insert method such as (in the case of a MySQL database):

<insert id= "Insert" parametertype= "Cn.hnne.iclt.model.Task" >
<selectkey resulttype= "Java.lang.Integer" keyproperty= "Ictl_otaid" order= "before" >
SELECT last_insert_id () as ID
</selectKey>
Insert INTO ...)
VALUES (...)
</insert>

But call this method directly, after the record is inserted, go to GetTaskID (), get null or 0.

Search on the Internet a lot of information there is no real solution, did not write to implement, and now write their own summary share.

First analyze the principle and then give the solution

Insert these fields: Resulttype is the return type when the query makes a select mapping. The parametertype in the configuration file can not be configured, and MyBatis is automatically passed in. These two are not the point.

Selectkey is the return of the primary key, in the action to obtain the primary key is through the Get method can be task.gettaskid (), but sometimes automatically generated to get;

Resolution: 1, inside the keyproperty= "otaid" field and entity (model) of the corresponding properties, this is the mybatis mapping mechanism.

2. The SELECT last_insert_id () as ID, not the property field name of the database, also gives the entity property name in model.

3, order= "before" if it is before that get the primary key before inserting, then is the initial value of NULL or 0.

Then set it after, which is to get the primary key value that automatically grows after inserting.

The following is the modified Mapper.xml code.

<insert id= "Insert" parametertype= "Cn.hnne.iclt.model.Task" >
<selectkey resulttype= "int" keyproperty= "Otaid" order= "after" >
SELECT last_insert_id () as Otaid
</selectKey>
Insert INTO .....
</insert>

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.