import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Example;
public class BaseHibernateDao {
private Session session=null;
private static SessionFactory sf;
public void setSession(Session session){
this.session=session;
}
protected Session getSession(){
if(session!=null){
return session;
}
else if(sf!=null){
session=sf.openSession();
return session;
}
Configuration cfg=new Configuration().configure();
sf=cfg.buildSessionFactory();
this.session=sf.openSession();
return session;
}
/* insert */
protected boolean add(Object item){
Session session=getSession();
Transaction tran=null;
boolean is=false;
try{
tran=session.beginTransaction();
session.save(item);
tran.commit();
is=true;
}catch(Exception e){
if(null!=tran)
tran.rollback();
e.printStackTrace();
}finally{
closeSession();
}
return is;
}
/* update */
protected boolean update(Object item){
Session session=getSession();
Transaction tran=null;
boolean is=false;
try{
tran=session.beginTransaction();
session.update(item);
tran.commit();
is=true;
}catch(Exception e){
if(tran!=null)
tran.rollback();
e.printStackTrace();
}finally{
closeSession();
}
return is;
}
/* delete (根据实体删除) */
protected boolean delete(Object item){
Session session=getSession();
Transaction tran=null;
boolean is=false;
try{
tran=session.beginTransaction();
session.delete(item);
tran.commit();
return is;
}catch (Exception e) {
if(tran!=null)
tran.rollback();
e.printStackTrace();
}finally{
closeSession();
}
return is;
}
/*根据主键删除(只能先查后删)*/
protected boolean delete(Class cls,java.io.Serializable id){
Session session = getSession();
boolean is =false;
try{
Object obj = select(cls, id);
session.delete(obj);
session.getTransaction().commit();
is=true;
}catch(HibernateException e){
if(null!=session)
session.getTransaction().rollback();
e.printStackTrace();
}
return is;
}
/* 根据主键查询 */
protected Object select(Class cls,java.io.Serializable id){
Object obj=null;
try {
obj = getSession().get(cls, id);
} catch (HibernateException e) {
e.printStackTrace();
} finally{
closeSession();
}
return obj;
}
/* select (根据对象查询:对象初始化的属性越多,查询条件越多) */
protected List select (Class clazz,Object obj){
List result= null;
try{
result=getSession().createCriteria(clazz).add(Example.create(obj)).list();
return result;
}catch(Exception e){
e.printStackTrace();
}finally{
closeSession();
}
return result;
}
/* 关闭session */
protected void closeSession(){
if(session!=null){
session.close();
session=null;
}
}
}