1、数据库的提交模式
数据库的提交主要分两种模式:手动和自动(还有一种情况是隐式的,即执行了connet等操作,也会提交)。它们分别的意义,自动提交不用你挂念最后要提交的问题,他会自动完成,并且每条语句被当成一个事务。手动提交,在你显示提交之前的所有语句都被认为是一个事务,它的好处是,当这个事务中的某一条语句失败时,事务会回滚,也就是都不会写到数据库,这有利于于保持数据库的一致性。
在不支持事务的数据库引擎中,每一条语句执行后就会自动提交,即使设置自动提交属性为false也不需要手动提交。Mysql数据库的默认提交方式是自动提交,可以使用命令查看select @@autocommit,1是自动提交,0是手动提交。
2、Hibernate commit和flush
先说一下两者的基本概念,首先commit,commit即提交数据库提交操作结果的过程;其次是flush,flush即清理缓存,执行sql语句的过程,但并不提交操作结果到数据库。在事务编程时,commit操作会先执行flush操作然后再提交,这时的flush可以不写。
基本配置代码;
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8</property>
<property name="hibernate.connection.username">*</property>
<property name="hibernate.connection.password">*</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/study/hibernate/hbm/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
2.1 非事务方式
基本测试代码:
<span style="font-size:14px;">private static void save(User u) {
Configuration cfg = new Configuration().configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session= sessionFactory.openSession();
session.save(u);
session.close();
}</span>
测试条件1:
1) Mysql Innodb 默认提交方式(自动提交)
3) 主键策略,identify/native
测试结果1:
数据库表格中没有记录
测试条件2:
1) Mysql Innodb 默认提交方式(自动提交)
2) Hibernate 设置自动提交方式,在基本配置中添加
3) 主键策略,identify/native
测试结果2:
数据库表格中有记录
测试条件3:
1) Mysql Innodb 默认提交方式(自动提交)
2) Hibernate 设置自动提交方式,在基本配置中添加
3) 主键策略,assigned/increment/uuid
测试结果3:
数据库表格中没有记录
测试条件4:
1) Mysql Innodb 默认提交方式(自动提交)
2) Hibernate 设置自动提交方式,在基本配置中添加
3) 主键策略assigned/increment/uuid
4) 在基本代码中session.save之后添加session.flush
测试结果4:
数据库表格中有记录2.2事务方式
基本测试代码:
<span style="font-size:14px;">private static void save(User u) {
Configuration cfg = new Configuration().configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session= sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(u);
transaction.commit();
session.close();
}
</span>
测试条件:
1) Mysql Innodb 默认提交方式(自动提交)
2) Hibernate 默认提交方式或者非自动提交
3) Session.flush可有可无
测试结果
数据库表格中有记录
3、总结
1)flush是清除缓存,发出sql语句到数据库并执行,但不会提交
2)flush操作的触发和主键策略相关
3)commit是提交操作结果,事务编程时commit调用默认会先调用flush,这时flush可以省略不写