Hibernate 帮助类

来源:互联网 发布:淘宝手机壳店铺 编辑:程序博客网 时间:2024/05/27 02:29
HibernateUtils.java
import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtils {private  static final String path="hibernate.cfg.xml";   private static final Configuration  cfg = new  Configuration();   private static SessionFactory sf=null;   private ThreadLocal<Session> thread =new  ThreadLocal<Session>();   static{   cfg.configure(path);     if(sf==null){     sf=cfg.buildSessionFactory();     }   }      public Session getSession(){    Session s=thread.get();    if(s==null){    s=sf.openSession();    thread.set(s);    }    return s;      }   public void CloseSession(){   Session s =thread.get();   if(s!=null){   s.close();   }         }}
BaseDao.java
import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;public class BaseDao  extends  HibernateUtils{//添加       public boolean add(Object obj){       Session s=null;       Transaction t=null;       try {s=super.getSession();   t=s.beginTransaction();   s.save(obj);   t.commit();   return true;} catch (HibernateException e) { t.rollback();}finally{this.CloseSession();}       return false;       }        //修改   public boolean update(Object obj){   Session s=null; Transaction t=null; try {s=super.getSession(); s.update(obj); t.commit(); return true;} catch (HibernateException e) {// TODO Auto-generated catch blockt.rollback();}       return false;       }     //通过Id删除   public boolean delete(int id){ Session s=null; Transaction t=null; try {s=super.getSession();  s.delete(id);  t.commit();  return true;} catch (HibernateException e) {       t.rollback(); }   return false;   }     //查询所有   public List getAll(String hql){   Session s=null;   s=this.getSession();    Query q =s.createQuery(hql);    List list =q.list();   return list;   }     //通过Id查询   public Object getById(Class cls,int id){   Session s=null;   s=this.getSession();   try {   Object o =s.get(cls, new Integer(id));   return o;} catch (HibernateException e) {e.printStackTrace();}finally{super.CloseSession();}   return null;   }   }

原创粉丝点击