关于SqlSession不提交事务对自增id的影响
来源:5-2 自由编程
Wonwayshon
2021-01-20 11:22:15
public void insertStudet() throws Exception {
SqlSession sqlSession = null;
try{
sqlSession=MybatisUtils.openSession();
Student student = new Student();
student.setRegNo(20171208);
student.setName("言豫津");
student.setSex("男");
student.setMajor("哲学系");
student.setGrade("2017");
student.setAge(26);
sqlSession.insert("student.insertStudent",student);
}catch(Exception e){
throw e;
}finally{
MybatisUtils.releaseSession(sqlSession);
}
}
上面代码中没有调用sqlSession.commit();对事务提交,jUnit执行完成后注意到数据库中没有插入新的数据,修改代码如下后再次执行,观察到数据库添加了数据但是自增id跳过了一位数字,我怀疑是之前没有提交的事务造成的,我的推测正确吗?像前面代码这样没有手动提交的事务Mybatis会定期自动提交吗?rollback()回滚事务会造成主键自增值的改变吗?
public void insertStudet() throws Exception {
SqlSession sqlSession = null;
try{
sqlSession=MybatisUtils.openSession();
Student student = new Student();
student.setRegNo(20171208);
student.setName("言豫津");
student.setSex("男");
student.setMajor("哲学系");
student.setGrade("2017");
student.setAge(26);
sqlSession.insert("student.insertStudent",student);
sqlSession.commit();
}catch(Exception e){
if(sqlSession!=null){
sqlSession.rollback();
}
throw e;
}finally{
MybatisUtils.releaseSession(sqlSession);
}
}
<insert id="insertGoods" parameterType="com.imooc.mybatis.entity.Goods">
INSERT t_goods VALUE(NULL,#{title},#{subTitle},#{originalCost},#{currentPrice},#{discount},#{isFreeDelivery},#{categoryId});
<selectKey resultType="Integer" keyProperty="goodsId">
SELECT last_insert_id();
</selectKey>
</insert>
1回答
同学你好
1、是的,同学的推测是正确的;id在缓存的时候已经创建,所以该id在缓存中已经存在,当再次执行代码时,自增id增加1,提交时用的最新的id
2、设置成手动提交后,不会自动提交
3、回滚事务也不会造成主键自增值的改变,回滚后,自增id仍然增加。
祝学习愉快~
相似问题