1 import org.hibernate.Session; 2 import org.hibernate.SessionFactory; 3 import org.hibernate.cfg.Configuration; 4 5 public class HibernateUtils { 6 7 // 1.创建工厂对象; 8 private static SessionFactory sessionFactory; 9 10 // 2.初始化工厂对象; 11 static { 12 sessionFactory = new Configuration().configure().buildSessionFactory(); 13 } 14 15 // 3.获得Session; 16 public static Session getSession() { 17 18 return sessionFactory.openSession(); 19 20 } 21 22 }
以上代码获得会话工厂类,但是会话开始之前要有一个开启事务,所以两者不能在一起使用,只能获取Session之后再开启事务;
For Example;
public class Demo1 { @Test public void demo1() { // // 5.开启事务; Session openSession = null; Transaction beginTransaction = null; try { openSession = HibernateUtils.getSession(); beginTransaction = openSession.beginTransaction(); // 6.操作数据库; Query createQuery = openSession.createQuery("from Admin"); System.out.println(createQuery.list()); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); // 7. 提交事务; beginTransaction.commit(); // 8 关闭资源; openSession.close(); } } }
源代码;
1 import org.hibernate.Query; 2 import org.hibernate.SessionFactory; 3 import org.hibernate.Transaction; 4 import org.hibernate.cfg.Configuration; 5 import org.hibernate.classic.Session; 6 import org.junit.Test; 7 8 public class Demo1 { 9 10 11 @Test 12 public void demo1() { 13 14 // 1.获取加载配置资源的对象; 15 Configuration configuration = new Configuration(); 16 // 2.加载资源配置; 17 // 当不写路径的时候,默认资源文件在src目录下; 18 configuration.configure(); 19 20 // 3.创建Session会话对象; 21 SessionFactory sessionFactory = configuration.buildSessionFactory(); 22 // 4.开启会话; 23 Session openSession = sessionFactory.openSession(); 24 // 5.开启事务; 25 Transaction beginTransaction = openSession.beginTransaction(); 26 // 6.操作数据库; 27 Query createQuery = openSession.createQuery("from Admin"); 28 29 System.out.println(createQuery.list().size()); 30 // 7. 提交事务; 31 beginTransaction.commit(); 32 // 8 关闭资源; 33 openSession.close(); 34 sessionFactory.close(); 35 36 } 37 38 }