package com.happybolin.mytest;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class AbstractDao {
private Session session;
private Transaction tr;
private Log log = LogFactory.getLog(AbstractDao.class);
public AbstractDao() {
HibernateUtil.buildSessionFactory();
}
protected void saveorUpdate(Object obj) {
try {
startOperation();
session.saveOrUpdate(obj);
tr.commit();
} catch (HibernateException e) {
log.error("saveorUpdate is fault");
} finally {
HibernateUtil.close(session);
}
}
protected void delete(Object obj) {
try {
startOperation();
session.delete(obj);
tr.commit();
} catch (HibernateException e) {
log.error("could not delete ");
} finally {
HibernateUtil.close(session);
}
}
protected Object find(Class clazz, Long id) {
Object obj = null;
try {
startOperation();
obj = session.load(clazz, id);
} catch (HibernateException e) {
log.error("find is fault");
} finally {
HibernateUtil.close(session);
}
return obj;
}
protected List findAll(Class clazz) {
List objects = null;
try {
startOperation();
Query query = session.createQuery("from clazz.getName");
objects = query.list();
tr.commit();
} catch (HibernateException e) {
log.error("findAll is fault");
} finally {
HibernateUtil.close(session);
}
return objects;
}
protected void startOperation() throws HibernateException {
session = HibernateUtil.openSession();
tr = session.beginTransaction();
}
}
hibernate BaseDao的几个方法
最新推荐文章于 2020-02-26 19:05:34 发布