我们项目升级Weblogic 9.1,所以可以用JDK5的东西了。
先试验一下GenericHibernateDAO,作为一个DAO的基类,实现了一些简单的方法,方便子DAO封装。
使用方法类似:
public class HibernateTownDAO extends GenericHibernateDAO<Town>
implements ITownDAO{
{
public HibernateTownDAO() { super(Town.class); } }
}
这个东西基本上是从EclipseWork里面来的……
IGenericDAO大家可以用Eclipse的抽出Interface……
代码如下:
package com.goldnet.dao.hibernateDAO;
import org.apache.commons.beanutils.BeanUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.goldnet.dao.IDAO.IGenericDAO;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
/**
* @author TIN
* @comment
* @param <E>
*
* 范型的抽象HibernateDAO,继承于Spring提供的HibernateDaoSupport,该DAO封装了大部分的Domain对象访问方法。
* 使用范型的目的在于可以显示的规定传入/返回的类型。直接的目的在于减少使用DAO时的强行类型转换。
*
* TODO:getTopsByProperty(int, String)方法
* TODO:execute(HibernateCallback callback)方法?
* TODO:execute(HQL hql)方法?
* TODO:execute(SQL sql)方法?
* TODO:findByCriteria(Criterion… criterion)方法?
* TODO:getAOfflineListCopy(List list)方法?获取一个离线list,可以在部分地方获取session无关的List,避免使用OpenSessionInView
* TODO:String getPersistentObjectName()方法?
* TODO:使用变长参数修改一些传入Properties和Value的地方,扩展一些方法
* TODO:研究一下DetachedCreteria
*
*/
public class GenericHibernateDAO<E> extends HibernateDaoSupport implements IGenericDAO<E> {
private static final long serialVersionUID = 1312483055446936306L;
private final Class clazz;
public GenericHibernateDAO(final Class<E> clazz) {
this.clazz = clazz;
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#saveOrUpdate(java.lang.Object,
* java.io.Serializable)
* @deprecated
*
* @param newObject 持久化的类
* @param id 持久化类的标识id
*
* 存储一个Entity,由于它的实现方式与HibernateDAO的saveOrUpdate雷同,都检测了id是否存在,但却多一个参数
* 所以暂时部推荐,但是该实现对saveOrUpdate机理表现比较清晰,所以没有删除
*/
public void saveOrUpdate(E newObject, Serializable id) {
if ((id != null) && !getHibernateTemplate().contains(id)) {
E dbObject = this.loadById(id);
try {
BeanUtils.copyProperties(dbObject, newObject);
} catch (Exception e) {
logger.error(e, e);
}
newObject = dbObject;
}
if (logger.isDebugEnabled()) {
logger.debug("[saveOrUpdate with id Parameter] Entity<"
+ this.clazz.getName() + ">.");
logger
.debug("this method is deprecated! Please use saveOrUpdate(Object) instead.");
}
getHibernateTemplate().saveOrUpdate(newObject);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#saveOrUpdate(java.lang.Object)
*
* @param newObject 持久化的类
*
* 持久化一个Entity,一般用在不知持久化的是VO或PO时
*/
public void saveOrUpdate(E newObject) {
if (logger.isDebugEnabled()) {
logger
.debug("[saveOrUpdate] Entity<" + this.clazz.getName()
+ ">.");
}
getHibernateTemplate().saveOrUpdate(newObject);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#save(java.lang.Object)
*
* @param object 持久化的类
*
* 持久化一个Entity,用在持久化PO时
*/
public void save(E object) {
if (logger.isDebugEnabled()) {
logger.debug("[save] Entity<" + this.clazz.getName() + ">.");
}
getHibernateTemplate().save(object);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#update(java.lang.Object)
*
* @param object 持久化的类
*
* 持久化一个Entity,符合jsr-220规范,用在持久化一个VO的Entity(但是它已经在库中存在)时,持久化它并返回它的PO
*/
@SuppressWarnings("unchecked")
public E merge(E object) {
if (logger.isDebugEnabled()) {
logger.debug("[merge] Entity<" + this.clazz.getName() + ">.");
}
return (E) getHibernateTemplate().merge(object);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#isEntityWithPropertyOfValueExist(java.lang.String,
* java.lang.Object)
*
* @param propertyName Entity属性的名称
* @param value Entity属性的值
* @return
*
* 具有propertyName的Entity是否存在?如果true则存在,如果false则不存在。
*/
public boolean isEntityWithPropertyOfValueExist(String propertyName,
Object value) {
if (logger.isDebugEnabled()) {
logger.debug("[isEntityWithPropertyOfValueExist] Entity<"
+ this.clazz.getName() + ">, propName=" + propertyName
+ ", value=" + value + ".");
}
if (getHibernateTemplate().find(
"from " + this.clazz.getName() + " table where table."
+ propertyName + "=?", value).size() > 0) {
return true;
}
return false;
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#isEntityIdExist(java.io.Serializable)
*
* @param id Entity的标识id
* @return
*
* 具有该id的Entity是否存在?如果true则存在,如果false则不存在。用来检测一个VO是否已经有对应的PO存在
*/
public boolean isEntityIdExist(Serializable id) {
if (logger.isDebugEnabled()) {
logger.debug("[isEntityIdExist] Entity<" + this.clazz.getName()
+ "> with id=" + id + ".");
}
return getHibernateTemplate().contains(id);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#delete(java.lang.Object)
*
* @param object Entity对象
*
* 删除一个Entity
*/
public void delete(E object) {
if (logger.isDebugEnabled()) {
logger.debug("[delete] Entity<" + this.clazz.getName() + ">.");
}
getHibernateTemplate().delete(object);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#deleteById(java.io.Serializable)
*
* @param id Entity的标识id
*
* 根据Entity的标识id删除一个Entity
*/
public void deleteById(Serializable id) {
if (logger.isDebugEnabled()) {
logger.debug("[deleteById] Entity<" + this.clazz.getName()
+ "> with id=" + id + ".");
}
getHibernateTemplate().delete(
getHibernateTemplate().get(this.clazz, id));
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#deleteByProperty(java.lang.String,
* java.lang.Object)
*
* @param propertyName Entity属性的名称
* @param value Entity属性的值
*
* 删除一组具有相同propertyName属性值(value)的Entity,用来批量删除
*/
@SuppressWarnings("unchecked")
public void deleteByProperty(String propertyName, Object value) {
Iterator<E> result = listByProperty(propertyName, value).iterator();
while (result.hasNext()) {
delete(result.next());
}
if (logger.isDebugEnabled()) {
logger.debug("[deleteByProperty] Entity<" + this.clazz.getName()
+ ">, propName=" + propertyName + ", value=" + value + ".");
}
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#loadById(java.io.Serializable)
*
* @param id Entity的标识id
* @return
*
* 根据Entity的标识id获取一个Entity的PO
*/
@SuppressWarnings("unchecked")
public E loadById(Serializable id) {
if (logger.isDebugEnabled()) {
logger.debug("[loadById] Entity<" + this.clazz.getName() + ">, id="
+ id + ".");
}
return (E) getHibernateTemplate().get(this.clazz, id);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#loadByProperty(java.lang.String,
* java.lang.Object)
*
* @param propertyName Entity属性的名称
* @param value Entity属性的值
* @return
*
* TODO:判断结果是否是unique?
* 获取一个具有相同propertyName属性值(value)的Entity,注意改属性必须是unique的,否则改方法将没有意义
*/
@SuppressWarnings("unchecked")
public E loadByProperty(String propertyName, Object value) {
Collection result = getHibernateTemplate().find(
"from " + this.clazz.getName() + " table where table."
+ propertyName + "=?", value);
Iterator<E> it = result.iterator();
if (logger.isDebugEnabled()) {
logger.debug("[loadByProperty] Entity<" + this.clazz.getName()
+ ">, propName=" + propertyName + ", value=" + value + ".");
}
if (it.hasNext()) {
return it.next();
} else {
return null;
}
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#loadEntitySum()
*
* @return
*
* 获取一种Entity的总数
*/
public int loadEntitySum() {
if (logger.isDebugEnabled()) {
logger.debug("[loadEntitySum] Entity<" + this.clazz.getName()
+ ">.");
}
return ((Integer) getHibernateTemplate().find(
"select count(*) from " + this.clazz.getName()).iterator()
.next()).intValue();
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#loadEntitySumByProperty(java.lang.String,
* java.lang.Object)
*
* @param propertyName Entity属性的名称
* @param value Entity属性的值
* @return
*
* 获取一组具有相同propertyName属性值(value)的Entity的个数
*/
public int loadEntitySumByProperty(String propertyName, Object value) {
if (logger.isDebugEnabled()) {
logger.debug("[loadEntitySum] Entity<" + this.clazz.getName()
+ ">, propName=" + propertyName + ", value=" + value + ".");
}
return ((Integer) getHibernateTemplate().find(
"select count(*) from " + this.clazz.getName()
+ " table where table." + propertyName + "=?", value)
.iterator().next()).intValue();
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#loadLastEntity()
*
* @param orderByPropertyName 用来排序的属性的名称
* @return
*
* TODO:和获取Tops是否重复?
* 返回最后一个Entity,用来获取如最新加入的Entity这样的方法
* 注意改方法实际上返回的是降序排列的list中的第一个!
*/
@SuppressWarnings("unchecked")
public E loadLastEntity(final String orderByPropertyName) {
if (logger.isDebugEnabled()) {
logger.debug("[listLastEntity] Entity<" + this.clazz.getName()
+ "> and orderByPropertyName=" + orderByPropertyName
+ ", Note:it’s DESC.");
}
return (E) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazz);
criteria.addOrder(Order.desc(orderByPropertyName));
releaseSession(session);
try {
return criteria.list().iterator().next();
} catch (Exception e) {
logger
.warn("[listLastEntity] faild! the entity list is empty!");
return null;
}
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listAll()
*
* @return
*
* 获取所有的Entity的list
*/
@SuppressWarnings("unchecked")
public Collection<E> listAll() {
if (logger.isDebugEnabled()) {
logger.debug("[listAll] Entity<" + this.clazz.getName() + ">.");
}
return getHibernateTemplate().find("from " + this.clazz.getName());
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listAllOrderBy(boolean, java.lang.String)
*
* @param isAsc 是否使用升序
* @param orderByPropertyName 排序的属性
* @return
*
* 获取所有的Entity的list,结果按照orderByPropertyName属性升序/降序(isAsc true则升序,否则降序)
*/
@SuppressWarnings("unchecked")
public Collection<E> listAllOrderBy(final boolean isAsc,
final String orderByPropertyName) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listAllOrderBy] Entity<" + this.clazz.getName()
+ ">, isAsc?=" + isAsc + ", orderByPropertyName="
+ orderByPropertyName + ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria.addOrder(isAsc ? Order
.asc(orderByPropertyName) : Order
.desc(orderByPropertyName));
releaseSession(session);
return criteria.list();
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByPage(int, int)
*
* @param pagesize 页的大小,每页最多Entity个数
* @param pageno 页码
* @return
*
* 获取一页的Entity的list,该页是所有Entity中的第pageno页,每页最多有pagesize个Entity,分页显示Entity时使用
*/
@SuppressWarnings("unchecked")
public Collection<E> listByPage(final int pagesize, final int pageno) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listByPage] Entity<" + this.clazz.getName()
+ ">, pagesize=" + pagesize + ", pageno=" + pageno + ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria.setFirstResult(pagesize * pageno);
criteria.setMaxResults(pagesize);
releaseSession(session);
return criteria.list();
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByPageOrderBy(int, int, boolean,
* java.lang.String)
*
* @param pagesize 页的大小,每页最多Entity个数
* @param pageno 页码
* @param isAsc 是否使用升序
* @param orderByPropertyName 排序的属性
* @return
*
* 获取一页的Entity的list,该页内容按照orderByPropertyName属性升序/降序(isAsc true则升序,否则降序),该页是所有Entity中的第pageno页,每页最多有pagesize个Entity
* 分页显示排序过的Entity时使用
*/
@SuppressWarnings("unchecked")
public Collection<E> listByPageOrderBy(final int pagesize,
final int pageno, final boolean isAsc,
final String orderByPropertyName) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listByPageOrderBy] Entity<" + this.clazz.getName()
+ ">, pagesize=" + pagesize + ", isAsc?=" + isAsc
+ ", orderByPropertyName" + orderByPropertyName
+ ", pageno=" + pageno + ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria
.setFirstResult(pagesize * pageno)
.setMaxResults(pagesize)
.addOrder(
isAsc ? Order.asc(orderByPropertyName)
: Order
.desc(orderByPropertyName));
releaseSession(session);
return criteria.list();
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByProperty(java.lang.String,
* java.lang.Object)
*
* @param propertyName Entity属性的名称
* @param value Entity属性的值
* @return
*
* 获取一组具有相同propertyName属性值(value)的Entity的列表list,返回一组符合条件的Entity
*/
@SuppressWarnings("unchecked")
public Collection<E> listByProperty(String propertyName, Object value) {
if (logger.isDebugEnabled()) {
logger.debug("[listByProperty] Entity<" + this.clazz.getName()
+ ">, propertyName" + propertyName + ", value=" + value
+ ".");
}
return getHibernateTemplate().find(
"from " + this.clazz.getName() + " table where table."
+ propertyName + "=?", value);
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByPageByProperty(java.lang.String,
* java.lang.Object, boolean, java.lang.String)
*
* @param pagesize 页的大小,每页最多Entity个数
* @param pageno 页码
* @param listByPropertyName Entity属性的名称
* @param value Entity属性的值
* @return
*
* 获取一页的Entity的list,该页内容为具有相同propertyName属性值(value)的Entity,该页是所有符合条件Entity中的第pageno页,每页最多有pagesize个Entity
* 分页显示匹配某一属性值的Entity时使用
*/
@SuppressWarnings("unchecked")
public Collection<E> listByPageByProperty(final int pageno,
final int pagesize, final String listByPropertyName,
final Object value) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listByPageByProperty] Entity<"
+ this.clazz.getName() + ">, pageno=" + pageno
+ ", pagesize=" + pagesize + ", listByPropertyName="
+ listByPropertyName + ", value" + value + ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria.setFirstResult(pagesize * pageno)
.setMaxResults(pagesize).add(
Restrictions.eq(listByPropertyName,
value));
releaseSession(session);
return criteria.list();
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByPropertyOrderBy(java.lang.String,
* java.lang.Object, boolean, java.lang.String)
*
* @param listByPropertyName Entity属性的名称
* @param value Entity属性的值
* @param isAsc 是否使用升序
* @param orderByPropertyName 排序的属性
* @return
*
* 获取所有的具有匹配propertyName属性值(value)的Entity的list,按照orderByPropertyName属性升序/降序(isAsc true则升序,否则降序)
* 显示匹配属性值的列表且要求排序时使用
*/
@SuppressWarnings("unchecked")
public Collection<E> listByPropertyOrderBy(final String listByPropertyName,
final Object value, final boolean isAsc,
final String orderByPropertyName) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listByPropertyOrderBy] Entity<"
+ this.clazz.getName() + ">, listByPropertyName="
+ listByPropertyName + ", value" + value + ", isAsc?="
+ isAsc + ", orderByPropertyName=" + orderByPropertyName
+ ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria
.add(Restrictions.eq(listByPropertyName, value))
.addOrder(
isAsc ? Order.asc(orderByPropertyName)
: Order
.desc(orderByPropertyName));
releaseSession(session);
return criteria.list();
}
});
}
/**
* @see com.goldnet.dao.IDAO.IGenericDAO#listByPageByPropertyOrderBy(int, int,
* java.lang.String, java.lang.Object, boolean, java.lang.String)
*
* @param pagesize 页的大小,每页最多Entity个数
* @param pageno 页码
* @param listByPropertyName Entity属性的名称
* @param value Entity属性的值
* @param isAsc 是否使用升序
* @param orderByPropertyName 排序的属性
* @return
*
* 获取一页的Entity的list,该页内容为具有相同propertyName属性值(value)的Entity,该页内容按照orderByPropertyName属性升序/降序(isAsc true则升序,否则降序),
* 该页是所有符合条件Entity中的第pageno页,每页最多有pagesize个Entity
* 分页显示匹配某一属性值的Entity时使用
*/
@SuppressWarnings("unchecked")
public Collection<E> listByPageByPropertyOrderBy(final int pagesize,
final int pageno, final String listByPropertyName,
final Object value, final boolean isAsc,
final String orderByPropertyName) {
final Class clazztemp = this.clazz;
if (logger.isDebugEnabled()) {
logger.debug("[listByPageByPropertyOrderBy] Entity<"
+ this.clazz.getName() + ">, pageno=" + pageno
+ ", pagesize=" + pagesize + ", listByPropertyName="
+ listByPropertyName + ", value" + value + ", isAsc?="
+ isAsc + ", orderByPropertyName=" + orderByPropertyName
+ ".");
}
return (Collection<E>) getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(clazztemp);
criteria
.setFirstResult(pagesize * pageno)
.setMaxResults(pagesize)
.add(Restrictions.eq(listByPropertyName, value))
.addOrder(
isAsc ? Order.asc(orderByPropertyName)
: Order
.desc(orderByPropertyName));
releaseSession(session);
return criteria.list();
}
});
}
}