MyBatis添加功能获取自增主键
准备
数据库t_Student表
Student类
MyBatis添加功能获取自增主键
接口
public interface StudentMapper {
int inserStudent(Student student);
}
映射文件
<?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>
说明: useGeneratedKeys="true"设置使用自增主键。keyProperty=“id”,其中的id即为自增主键,也就是Student类中的id属性。
测试
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//创建需要插入的对象
Student st = new Student("小明",10,"男");
//调用插入函数
int i = mapper.inserStudent(st);
//输出主键
System.out.println(st.getId());
输出结果