Hibernate的Dao的封装

来源:互联网 发布:ubuntu 修改apt get源 编辑:程序博客网 时间:2024/05/24 02:32
package cn.com.bochy.dao;
import java.util.List;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateUntil<T> {
  private SessionFactory sf;
  private Session session;
  @SuppressWarnings("deprecation")
  //1、获取SessionFactory
public SessionFactory getSF(){
 //读取Hibernate配置文件
 Configuration cfg=new Configuration().configure();
 //获取SessionFactory
  sf=cfg.buildSessionFactory();
 return sf;
  }
  //2、获取session
  public Session getSession(){
 getSF();
 session=sf.openSession();
 return session;
  }
  
@SuppressWarnings("unchecked")
//3、封装成list
public List<T> getList(String hql){
 getSession();
 Query query=session.createQuery(hql);
 List<T> lis=query.list();
closeAll();
return lis;
 
  }
  //4、添加
  public boolean Save(T obj){
 getSession();
 Transaction tx=session.beginTransaction();
 boolean mark=true;
 try {
session.save(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
 closeAll();
return mark;
 
  }
  //5、修改
  public boolean update(T obj){
 getSession();
 Transaction tx=session.beginTransaction();
 boolean mark=true;
 try {
session.saveOrUpdate(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
 closeAll();
return mark;
 
  }
  //6、根据id,获取实体对象
  public T getObjectById(int id,Class<T> c){
 getSession();
@SuppressWarnings("unchecked")
T obj=(T)session.get(c, id);
closeAll();
return obj ;
 
  }
  //7、删除
  public boolean delete(T obj){
 getSession();
 Transaction tx=session.beginTransaction();
 boolean mark=true;
 try {
session.delete(obj);
tx.commit();
} catch (Exception e) {
// TODO Auto-generated catch block
mark=false;
e.printStackTrace();
tx.rollback();
}
 closeAll();
return mark;
 
  }
  //8、关闭资源
  public void closeAll(){
 if(session!=null){
 session.close();
 }
 if(sf!=null){
 sf.close();
 }
  }
}