代码间接放在Github仓库【https://github.com/Damaer/Myb...】,mybatis-02可间接运行,就不占篇幅了。
为什么咱们有时候不应用commit也能批改数据库胜利?
[TOC]
1.从数据库的层面上来讲,其实这个次要看你用什么“存储引擎”
像以下的代码就是应用了主动提交的mysql引擎。
CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , `age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;
如果是不反对事务的引擎,如myisam,则是否commit都没无效的。
如果是反对事务的引擎,如innodb,则有零碎参数设置是否主动commit,查看参数如下:
mysql> show variables like '%autocommit%';+---------------+-------+| Variable_name | Value |+---------------+-------+| autocommit | ON |+---------------+-------+1 row in set (0.00 sec)mysql>
显示后果为on示意事务主动提交,不必手工去commit,当然,你能够设置其为OFF,而后本人手工去commit。
2.应用myIsam引擎,不须要commit
比方上面的代码:
public class StudentDaoImpl implements IStudentDao { private SqlSession sqlSession; public void insertStu(Student student) { try { InputStream inputStream; inputStream = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); sqlSession.insert("insertStudent",student); } catch (IOException e) { e.printStackTrace(); } }}
咱们能够看到曾经更新了一行,咱们齐全不应用commit
3.创立数据表(应用Innodb),也不提交,后果没有插入
CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , `age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = Innodb;
咱们再执行插入时,发现控制台输入是这样的:
如同输出也胜利了,然而我去数据库看了一下,竟然是空的:
那咱们将代码换成这样,退出提交事务:
public class StudentDaoImpl implements IStudentDao { private SqlSession sqlSession; public void insertStu(Student student) { try { InputStream inputStream; inputStream = Resources.getResourceAsStream("mybatis.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); sqlSession=sqlSessionFactory.openSession(); sqlSession.insert("insertStudent",student); // 提交事务 sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); }finally { if(sqlSession!=null){ sqlSession.close(); } } }}
执行代码,咱们会发现事务提交胜利了,同时咱们也敞开数据库了:
关上数据库,咱们会发现,竟然没有id为1的记录,为什么间接跳到2了呢?还记不记得之前插入一次然而没有提交,所以问题就在这里。上一次的提交曾经写到事务外面了,只是没有提交,所以这一次提交的时候,上一次默认曾经占用了那条记录,只是不写进数据库中。有提交就能够回滚,所以要应用回滚的话,能够应用sqlsession.rollback()
。
如果咱们应用sqlsession.close()的话,咱们就不须要应用回滚了。
上面是我把commit去掉,然而留下close的后果,咱们能够看到没有commit,然而曾经会主动rollback了,所以只有应用sqlsession.close()
就会主动回滚再敞开。
【作者简介】:
秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使迟缓,驰而不息。这个世界心愿所有都很快,更快,然而我心愿本人能走好每一步,写好每一篇文章,期待和你们一起交换。
此文章仅代表本人(本菜鸟)学习积攒记录,或者学习笔记,如有侵权,请分割作者核实删除。人无完人,文章也一样,文笔稚嫩,在下不才,勿喷,如果有谬误之处,还望指出,感激不尽~