前段时间,在javaeye中关于这个的讨论内容很多,正好我在优化我的dao基类,想把dao做成通用的,所以借鉴了大家的思想和代码.
一直在潜水,很不好意思,决定把我的实现发在这里,贡献给大家,有什么不妥的欢迎指正.
关于通用dao的优缺点这里不谈,只说实现
现在还有两个问题很头疼,先看代码
[code=java]
package org.sigon.framework.dao;
import
/**
* dao基类
*
* @author sigon
*
*/
public class BaseDao extends
HibernateDaoSupport {
private Class poClass = null;
private Class voClass = null;
public BaseDao(Class poClass, Class voClass){
this.poClass = poClass;
this.voClass = voClass;
}
/**
* 存储po对象
*
* @param entity
* @throws Exception
*/
protected void save(PO entity) throws Exception {
this.getHibernateTemplate().save(entity);
}
public void saveUseVO(VO vo) throws Exception{
PO po = getPOClass().newInstance();
BeanUtils.copyProperties(vo, po);
save(po);
}
protected void saveOrUpdate(PO entity) throws Exception {
this.getHibernateTemplate().saveOrUpdate(entity);
}
/**
* 删除po
*/
protected void delete(Serializable id) throws Exception {
PO entity = get(id);
this.getHibernateTemplate().delete(entity);
}
/**
* 更新po
*/
protected void update(VO vo) throws Exception {
PO entity = getPOClass().newInstance();
BeanUtils.copyProperties(vo, entity);
this.getHibernateTemplate().update(entity);
}
/**
* 取出po并且使对象脱离缓存
*/
protected PO getAndEvict(Serializable id)
throws Exception {
PO result = get(id);
this.getHibernateTemplate().evict(result);
return result;
}
/**
* 按id取对象
*/
@SuppressWarnings("unchecked")
protected PO get(Serializable id)
throws Exception {
return (PO)this.getHibernateTemplate().get(getPOClass(), id);
}
public VO getVO(Serializable id) throws Exception{
PO po = get(id);
return convertPO2VO(po);
}
//
/**
* 取出po列表,按hql
*/
@SuppressWarnings("unchecked")
protected List find(String hql) throws Exception {
return getHibernateTemplate().find(hql);
}
/**
* 执行带参数的hql
*/
@SuppressWarnings("unchecked")
protected List find(String hql, Object... params) throws Exception {
return getHibernateTemplate().find(hql, params);
}
/**
* qbc式查询list
*/
@SuppressWarnings("unchecked")
protected List findListByQBC(DetachedCriteria criteria)
throws Exception {
return getHibernateTemplate().findByCriteria(criteria);
}
//
// /**
// * qbc式查询对象
// */
// @SuppressWarnings("unchecked")
// protected PO findObjectByQBC(final DetachedCriteria criteria)
// throws Exception {
// return (PO) getHibernateTemplate().execute(new HibernateCallback() {
// public Object doInHibernate(Session session)
// throws HibernateException, SQLException {
// return criteria.getExecutableCriteria(session).uniqueResult();
// }
// }, true);
// }
/**
* 根据属性值查找
*
* @param entityClass
* @param propertyName
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public List findByProperty(String propertyName,
Object value) throws Exception{
List poList = createCriteria(Restrictions.eq(propertyName, value)).list();
return convertListPO2VO(poList);
}
/**
* 按属性查找唯一对象.
*/
@SuppressWarnings("unchecked")