Mybatis gets the self growing field value (ID) of the inserted record
Step 1:
Add the properties "usegeneratedkeys" and "keyproperty" in the mybatis mapper file, where keyproperty is the property name of the Java object!
Step 2:
After mybatis executes the insert statement, it automatically assigns the self increasing value to the property ID of the object sparks. Therefore, it can be obtained through the getter method corresponding to spares!
PS: mybatis returns the self growing ID of the inserted data
Today, a bug was reported in the test. The phenomenon is that newly registered users can see everyone's report, and the old users have no problem. When checking the log, it was found that the ID of the newly registered user was null, so the full table valid data query was carried out. However, the primary key of the table cannot be empty. How can a new registered user id be null? The reason is that in the service layer, the code directly returns the parameter object without any configuration in XML.
The specific solution is to configure the insert method in XML
The keyproperty value corresponds to the primary key property in the entity VO object
The details are as follows:
registermapper. The insert method of XML is as follows:
Execute the normal insert statement
In this way, the self growing primary key of the newly inserted data can be obtained in the controller layer.
The online explanation of the meaning of adding two attributes to XML is as follows:
useGeneratedKeys
(only useful for insert) this will tell mybatis to use the getgeneratedkeys method of JDBC to retrieve the primary key generated internally by data (such as the auto increment field of database management systems such as MySQL and SQL Server). Default: false.
keyProperty
(only useful for insert) mark an attribute. Mybatis will set its value through getgeneratedkeys or the selectkey sub element of the insert statement. Default: not set.
summary
The above is what Xiaobian introduced to you. Mybatis obtains the self growth field value (ID) of the inserted record. I hope it will be helpful to you. If you have any questions, please leave me a message, and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!