通过该工具类可以获得hibernate的session对象,并在项目中使用该工具
public class MyHibernateUtil { private static SessionFactory sessionFactory; //表示构造方法私有化,保证单例模式 private MyHibernateUtil(){ } /** * @return 获取会话工厂 */ public static SessionFactory getSessionFactory() { if(sessionFactory ==null){ //第一步:读取Hibernate的配置文件 hibernamte.cfg.xml文件 Configuration con=new Configuration().configure(); //第二步:创建服务注册构建器对象,通过配置对象中加载所有的配置信息 ServiceRegistryBuilder regbulider=new ServiceRegistryBuilder().applySettings(con.getProperties()); //创建注册服务 ServiceRegistry reg=regbulider.buildServiceRegistry(); //第三步:创建会话工厂 SessionFactory sessionFactory=con.buildSessionFactory(reg); return sessionFactory; }else { return sessionFactory; } } }
简单使用:
public boolean usersLogin(Users u) { Transaction tx=null; String hql=""; try { Session session = MyHibernateUtil.getSessionFactory() .getCurrentSession(); hql = "from Users where username=? and password=?"; tx =session.beginTransaction(); Query query = session.createQuery(hql); query.setParameter(0, u.getUsername()); query.setParameter(1, u.getPassword()); List list = query.list(); tx.commit(); if(list.size() > 0){ return true; }else { return false; } } catch (Exception e) { e.printStackTrace(); return false; }finally{ if(tx != null){ tx = null; } } }
MyHibernateSessionFactory