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>