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 ()