Hibernate的事務管理:java
1、開啓自動提交事務數據庫
<property name="hibernate.connection.autocommit">true</property><!-- 自動提交事務 -->
一、 當自動提交事務爲開啓時:不手動開啓事務,數據持久化到數據庫。session
Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); //Transaction transaction = session.beginTransaction(); TbUser user = new TbUser(); user.setName("ceshi2"); user.setAge(15L); user.setCity("sjz1"); session.save(user); //transaction.commit(); session.close(); sessionFactory.close();
數據被持久化到數據庫:app
二、 當自動提交事務爲開啓時:手動開啓事務,強制提交事務數據持久化到數據庫。ui
Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); TbUser user = new TbUser(); user.setName("ceshi2"); user.setAge(15L); user.setCity("sjz1"); session.save(user); //transaction.commit(); session.close(); sessionFactory.close();
數據沒有被持久化到數據庫,可是序列已經被讀取。hibernate
2、沒有開啓自動提交事務code
<!-- 自動提交事務 --> <!-- <property name="hibernate.connection.autocommit">false</property> -->
一、手動開啓事務數據被持久化到數據庫。事務
二、不手動開啓事務,數據沒有被持久化到數據庫,但序列增長。get