automatically generate primary key in MyBatisIn the INSERT statement, we insert a value for the column that can automatically generate (auto-generated) the primary key stud_id. We can use the Usegeneratedkeys and Keyproperty properties to let the database generate the value of the Auto_increment column and set the generated value to one of the input object properties, as follows:
<insert id= "insertstudent" parametertype= "Student" usegeneratedkeys= "true" keyproperty= "Studid" >
Insert Into STUDENTS (NAME, EMAIL, PHONE) VALUES (#{name},#{email},#{phone})
Here the stud_id column value will be automatically generated by the database (such as MySQL), and the generated value will be set to the Studid property of the student object.
However, some databases, such as Oracle, do not support auto_increment columns, which use sequences (SEQUENCE) to generate primary key values. Suppose we have a sequence named My_seq to generate the SUTD_ID primary key value. Use the following code to generate the primary key:
Drop sequence my_seq;
Create sequence my_seq;
<insert id= "insertstudent" parametertype= "Student" >
<selectkey keyproperty= "Studid" resulttype= "int" Order= "Before" >
SELECT my_seq.nextval from DUAL
</selectKey>
INSERT into STUDENTS (stud_id,name , EMAIL, PHONE)
VALUES (#{studid},#{name},#{email},#{phone})
</insert>
Here we use the <selectKey> child element to generate the primary key value and save the value to the Studid property of the student object. The property order= "before" indicates that MyBatis takes the next value of the obtained sequence as the primary key value and sets the value to the Studid property before the INSERT statement is executed.
Note: Selectkey need to pay attention to the order attributes, such as MySQL, SQL Server and other types of support for the automatic growth type of the database, the order needs to be set to after the correct value will be taken.
such as Oracle to take a sequence of circumstances, need to set to before, otherwise it will be an error.