封装一个简单的Hibernate SessionFactory
封装Hibernate框架中的session工厂 ,方便很多,免去了很多重复无用的代码
package com.maya.test; import org.hibernate.*; import org.hibernate.cfg.*; public class HibernateUtil { private static final SessionFactory factory=buildFactory(); //建一个session工厂,调用方法构建出 private static final ThreadLocal<Session> threadlock=new ThreadLocal<Session>(); //保证线程安全,构建一个线程锁,保证该线程未结束前不会被占用 public static SessionFactory buildFactory() { Configuration config=new Configuration(); return config.buildSessionFactory(); } public static Session getSession(){ Session session=threadlock.get();//获取线程锁中的session if(session==null){ //如果session是空的,打开一个session session=factory.openSession(); } threadlock.set(session); //将session放入线程锁中,保证该线程不会被干扰 return session; } public static void closeSession(){ //该方法为关闭session,获取session 如果不为空,那么关闭,并且将线程锁更改为空 Session session=threadlock.get(); if(session!=null){ session.close(); threadlock.set(null); } } }
调用:
package com.maya.test; import org.hibernate.*; import org.hibernate.cfg.*; import com.maya.model.Family; public class FamilyTest { public static void main(String[] args){ Family fa=new Family(); fa.setName("小明"); fa.setFirm("召唤师峡谷"); fa.setInfoCode("p003"); Session session=HibernateUtil.getSession();//获取session try{ session.beginTransaction(); session.save(fa); session.getTransaction().commit(); } catch(Exception e){ session.getTransaction().rollback(); } finally{ HibernateUtil.closeSession(); } } }
我们不是制造者,我们是代码搬运工