MyBatis is used to obtain the auto-generated primary key Id and instance code.
MyBatis obtains the auto-generated primary key Id and instance code.
When using a MySQL database, we generally use the auto-incrementing primary key of the database to automatically generate a primary key. If we need to insert data from the table at the same time when inserting the primary table, we usually need to know the primary key Id value automatically generated when inserting the primary table.
The following describes how to obtain the self-generated primary key of the database during MyBatis insertion:
1. XML configuration file
<Insert id = "insert" parameterType = "Person" useGeneratedKeys = "true" keyProperty = "id"> insert into person (name, pswd) values (# {name }, # {pswd}) </insert>
2. Mapper Methods
Int insert (Person person );
Note that when calling this method, the returned int value is not the primary key, but the number of records inserted. The primary key id is assigned to the input person object and is automatically assigned to the id attribute of the person object. For example:
Person person = new Person ("name", "psw"); // num indicates the number of records inserted. int num = PersonMapper. insert (person); // The id attribute of the person object is changed to the self-generated idint id = person. getId ();
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!