实体类对象在Hibernate中有3种状态:
1 import cn.fereli.model.Category; 2 import org.hibernate.Session; 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 6 /** 7 * 8 * hibernate的基本步骤是: 9 * 1. 获取SessionFactory 10 * 2. 通过SessionFactory 获取一个Session 11 * 3. 在Session基础上开启一个事务 12 * 4. 通过调用Session的save方法把对象保存到数据库 13 * 5. 提交事务 14 * 6. 关闭Session 15 * 7. 关闭SessionFactory 16 * @author fereli 17 */ 18 public class TestHibernate1 { 19 public static void main(String[] args) { 20 //1. 获取SessionFactory 21 SessionFactory sf = new Configuration().configure().buildSessionFactory(); 22 //2. 通过SessionFactory 获取一个Session 23 Session s = sf.openSession(); 24 //3. 在Session基础上开启一个事务 25 s.beginTransaction(); 26 // 4. 通过调用Session的save方法把对象保存到数据库 27 Category category = new Category(); 28 category.setName("分类1"); 29 /*——————————此时category是瞬时——————————*/ 30 System.out.println("category是瞬时"); 31 s.save(category); 32 /*——————————此时category是持久——————————*/ 33 System.out.println("category是持久"); 34 //5.提交事务 35 s.getTransaction().commit(); 36 //6.关闭Session 37 s.close(); 38 /*——————————此时category是托管——————————*/ 39 System.out.println("category是托管"); 40 //关闭SessionFactory 41 sf.close(); 42 } 43 44 }
原文:https://www.cnblogs.com/Fereli/p/12081366.html