创建单例模式
package cn.hrbust.dao; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtils { private static Configuration cfg = null; private static SessionFactory sf = null; static { try { cfg = new Configuration().configure();//读取配置文件 sf = cfg.buildSessionFactory();// 创建SessionFactory } catch (HibernateException e) { e.printStackTrace(); } } public static SessionFactory getSessionFactory(){ return sf; } public static void close() { sf.close(); } }
保存
@Test public void testSavaUser() { Configuration cfg = null; SessionFactory sf = null; Session session = null; Transaction ts = null; User u = new User(); u.setName("陈陈"); u.setGender("男"); u.setAge(23); u.setBirthday(Date.valueOf("1998-12-18")); try { sf = HibernateUtils.getSessionFactory(); session = sf.getCurrentSession(); ts = session.beginTransaction(); session.save(u); ts.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); if(ts != null) { ts.rollback(); } } }
运行结果
查询
@Test public void testQueryUser() { SessionFactory sf=null; Session session =null; Transaction ts=null; try { sf=HibernateUtils.getSessionFactory();//SessionFactory单态模式 session =sf.getCurrentSession(); //保证每个读写线程有唯一的session实例 ts=session.beginTransaction(); Query query=session.createQuery("from User");//类名 List<User> users =query.list(); for(User u:users) { System.out.println(u.getName()+" "+u.getGender()+" "+u.getAge()+" "+u.getBirthday()); } ts.commit(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); if(ts!=null) { ts.rollback(); } } }
运行结果