MyBatis adds the function to get the auto-incrementing primary key
Prepare
Database t_Student table
Student class
MyBatis adds the function to get the auto-incrementing primary key
interface
public interface StudentMapper {
int inserStudent(Student student);
}
map file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!--约束,约束不同xml中所写的标签也不同-->
<mapper namespace="com.xxx.mapper.StudentMapper"><!--接口-->
<!-- int inserStudent(Student student); -->
<insert id="inserStudent" useGeneratedKeys="true" keyProperty="id">
insert into t_student values(null,#{name},#{age},#{sex})
</insert>
</mapper>
Description: useGeneratedKeys="true" sets the use of auto-incrementing primary keys. keyProperty="id", where id is the self-incrementing primary key, which is the id attribute in the Student class.
test
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//创建需要插入的对象
Student st = new Student("小明",10,"男");
//调用插入函数
int i = mapper.inserStudent(st);
//输出主键
System.out.println(st.getId());
output result