1.最简单的工具类,实现SessionFactory的单例共享,session的管理
package com.cc.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { //创建工厂类,是静态的单例的,只能被赋值一次 private static final SessionFactory sessionFactory=buildSessionFactory(); /** init sessionFactory */ private static SessionFactory buildSessionFactory(){ SessionFactory sessionFactory=null; try{ //configure函数里面可以写hibernate的配置文件,空则默认为hibernate.cfg.xml Configuration configuration=new Configuration().configure(); ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory= configuration.buildSessionFactory(serviceRegistry); } catch(Throwable te){ System.err.println("init sessionFactory Error:"+te); te.printStackTrace(); } return sessionFactory; } /** get session */ public static Session getSession(){ //得到session Session session=sessionFactory.openSession(); return session; } }
2.将常见事务方法封装进工具类
添加如下方法:
//删除 public static boolean delete(Object obj){ Session session=null; Transaction tran=null; boolean result=false; try{ session=getSession(); tran=session.beginTransaction(); session.delete(obj); tran.commit(); result=true; } catch (Exception e){ if(tran!=null){ //事物回滚 tran.rollback(); } } finally{ if(session!=null){ //关闭session session.close(); } } return result; } //更新 public static boolean update(Object object) { Session session=null; Transaction tran=null; boolean result=false; try{ session=getSession(); tran=session.beginTransaction(); session.update(object); tran.commit(); result=true; } catch (Exception e){ if(tran!=null){ //事物回滚 tran.rollback(); } } finally{ if(session!=null){ //关闭session session.close(); } } return result; } //增加 public static boolean add(Object obj){ Session session=null; Transaction tran=null; boolean result=false; try{ session=getSession(); tran=session.beginTransaction(); session.save(obj); tran.commit(); result=true; } catch (Exception e){ if(tran!=null){ //事物回滚 tran.rollback(); } } finally { if(session!=null){ //关闭session session.close(); } } return result; } //执行sql语句,返回单条记录 public static Object queryOne(String sql,String[] param){ Object object=null; Session session=null; try{ session=getSession(); Query query=session.createQuery(sql); if(param!=null){ for(int i=0;i<param.length;i++){ query.setString(0,param[i]); } object=query.uniqueResult(); } } catch (Exception e){ } finally{ if(session!=null){ session.close(); } } return object; }
参考:http://blog.csdn.net/hanhan313/article/details/8125924
时间: 2024-10-11 06:34:25