hibernate整合的工具类HibernateUtil----单例模式

package com.lanou.mp.util;


import java.io.Serializable;
import java.util.List;
import java.util.Map;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;


public class HibernateUtil {
// 单例模式 饿汉单例模式、
private static HibernateUtil instance;// 共享
private Configuration config;
private SessionFactory sf;// 只有一个
        //该类构造方法,里面加载了config对象,是为了调用时就加载配置文件,创建sessionfactory工厂,此工厂在整个系统中只有一个
private HibernateUtil() {
config = new Configuration().configure();
sf = config.buildSessionFactory();
}
   //封装的方法返回session对象
public Session getCurrentSession() {
return sf.getCurrentSession();
}
   //单例模式的重要体现 ,调用该方法返回该类对象
public static HibernateUtil getInstance() {
if (instance == null) {
instance = new HibernateUtil();
}
return instance;
}
   //查询有条件的hql,此方法用到类泛型,list里面调用时hql传的是条件处的?
public <T> List<T> execute(String hql, List<String> parm) {
Session session = null;
Transaction tx = null;
try {
session = getCurrentSession();
tx = session.beginTransaction();
Query<T> query = session.createQuery(hql);
for (int i = 0; i < parm.size(); i++) {
query.setParameter(i, parm.get(i));
}
List<T> list = query.getResultList();


tx.commit();
return list;
} catch (Exception e) {
e.printStackTrace();
tx.rollback();
return null;
} finally {
session.close();
}


}
//根据id查询
public <A> A getOne(Class<A> temp, Serializable id) {
Session session = null;
Transaction tx = null;
try {
session = this.getCurrentSession();
tx = session.beginTransaction();
A a = session.get(temp, id);


tx.commit();
return a;
} catch (Exception e) {
e.printStackTrace();
return null;


}


}

}
展开阅读全文

没有更多推荐了,返回首页