1. The database supports automatic generation of primary keys
If the database supports fields that automatically generate primary keys (such as MySQL and SQL Server), you can set useGeneratedKeys="true", and then set keyProperty to the target property.
- mysql supports self-incrementing primary keys and the acquisition of self-incrementing primary key values. Mybatis also uses statement.getGenreatadKeys();
- useGeneratedKeys=”true”: Use the auto-incrementing primary key to obtain the primary key value strategy.
- keyProperty: Put the acquired auto-increment primary key into which property value of the Javabean.
<insert id="addEmployee" useGeneratedKeys="true" keyProperty="id" databaseId="mysql">
insert into employee(last_name,age,email)
values(#{lastName},#{age},#{email})
</insert>
2. The database does not support the automatic generation of primary keys
For databases that do not support auto-incrementing primary keys (eg Oracle), you can use the selectKey sub-element: the selectKey element will run first, the id will be set, and then the insert statement will be called.
Oracle does not support auto-increment; Oracle uses sequence to simulate auto-increment; the primary key of each inserted data is obtained from the sequence.
<insert id="addEmployee" databaseId="oracle">
<selectKey keyProperty="id" order="BEFORE" resultType="Integer">
select EMPLOYEE_SEQ.nextval from dual
</selectKey>
<!-- 插入的主键是从序列中获取的 -->
insert into employee(id,last_name,age,email)
values(#{id},#{lastName},#{age},#{email})
</insert>
After the configuration of the above XML file, the ID of the record can be obtained when inserting data.
@Test
public void testInsert() {
try {
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
//插入前,ID 属性是 null
Employee emp = new Employee(null, "EE", 25, "[email protected]");
mapper.addEmployee(emp);
//执行完插入操作后可以获取该条记录的 ID
System.out.println("ID:" + emp.getId());
sqlSession.commit();
} finally {
sqlSession.close();
}
}