自增主键返回:
Mysql自增主键,它是在insert语句执行之前,自动生成一个自增主键值,通过mysql函数LAST_INSERT_ID();可以获得插入记录的自增主键值。
使用mybatis框架获取自增主键id方法:
第一种方式:开启逆向获取主键值
<!-- useGeneratedKeys="true" 开启自增主键策略 keyProperty="id" 将获取的主键值封装到类的id属性当中 -->
<insert id="addEmp" parameterType="employee" useGeneratedKeys="true" keyProperty="id">
insert into tbl_employee(last_name,gender,email) values (#{lastName},#{gender},#{email})
</insert>
测试:
@Test
public void test2() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = null;
try {
//无参的openSession()获取的sqlSession是不会自动提交数据,执行增删改操作的时候,我们需要手动提交
sqlSession = sqlSessionFactory.openSession();
//有参的openSession(true)会自动提交事务,我们不需要手动提交
//sqlSessionFactory.openSession(true);
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
//添加
employee.setLastName("亚索");
employee.setEmail("22@qq.com");
employee.setGender("0");
System.out.println("新增之前的实体类id:"+employee.getId());
Integer integer = mapper.addEmp(employee);
System.out.println("新增之后的实体类id:"+employee.getId());
//手动提交
sqlSession.commit();
} finally {
sqlSession.close();
}
}
第二种方式:
<insert id="addEmp" parameterType="employee">
<selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into tbl_employee(last_name,gender,email) values (#{lastName},#{gender},#{email})
</insert>
[selectKey标签]:通过select查询来生成主键
[keyProperty]:指定存放生成主键的属性
[resultType]:生成主键所对应的Java类型
[order]:指定该查询主键SQL语句的执行顺序,相对于insert语句
[last_insert_id]:MySQL的函数,要配合insert语句一起使用
keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性(上述user对象的id属性)
order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型
@Test
public void test2() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = null;
try {
//无参的openSession()获取的sqlSession是不会自动提交数据,执行增删改操作的时候,我们需要手动提交
sqlSession = sqlSessionFactory.openSession();
//有参的openSession(true)会自动提交事务,我们不需要手动提交
//sqlSessionFactory.openSession(true);
EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
//添加
employee.setLastName("亚索");
employee.setEmail("22@qq.com");
employee.setGender("0");
System.out.println("新增之前的实体类id:"+employee.getId());
Integer integer = mapper.addEmp(employee);
System.out.println("新增之后的实体类id:"+employee.getId());
//手动提交
sqlSession.commit();
} finally {
sqlSession.close();
}
}