packageorg.usc.daos.base;
importjava.beans.Introspector;
importjava.beans.PropertyDescriptor;
importjava.io.Serializable;
importjava.lang.reflect.Method;
importjava.sql.SQLException;
importjava.util.LinkedHashMap;
importjava.util.List;
importjavax.annotation.Resource;
importjavax.persistence.EmbeddedId;
importjavax.persistence.Entity;
importorg.hibernate.HibernateException;
importorg.hibernate.Query;
importorg.hibernate.Session;
importorg.hibernate.SessionFactory;
importorg.springframework.orm.hibernate3.HibernateCallback;
importorg.springframework.orm.hibernate3.support.HibernateDaoSupport;
importorg.usc.beans.base.QueryResult;
importorg.usc.utils.base.GenericsUtils;
/**
* DAO层封装使用了泛型,包含常用的CURD和分页操作
*
*@authorShunLi
*@notesCreated on 2010-1-24
* Revision of last commit:$Revision: 650 $
*Author of last commit:$Author: nhjsjmz@gmail.com $
*Date of last commit:$Date: 2010-03-09 20:44:14 +0800 (周二, 09三月2010) $
*
*/
@SuppressWarnings("unchecked")
publicabstractclassBaseDaoSupportextendsHibernateDaoSupportimplementsIBaseDao
{
protectedClassentityClass= GenericsUtils.getSuperClassGenricType(this.getClass());
protectedStringentityClassName= getEntityName(this.entityClass);
protectedStringkeyFieldName= getKeyFieldName(this.entityClass);
//为父类HibernateDaoSupport注入sessionFactory的值
@Resource(name ="sessionFactory")
publicvoidsetSuperSessionFactory(SessionFactory sessionFactory)
{
super.setSessionFactory(sessionFactory);
}
/*
* @see org.usc.daos.DAO#findByEntity(java.lang.Object)
*/
publicList findByEntity(Object entiey)
{
returnsuper.getHibernateTemplate().findByExample(entiey);
}
/*
* @see org.usc.daos.DAO#findByProperty(java.lang.String, java.lang.Object)
*/
publicList findByProperty(String propertyName, Object value)
{
String queryString ="from "+entityClassName+" o where o."+ propertyName +"= ?";
returnsuper.getHibernateTemplate().find(queryString, value);
}
/*
* @see org.usc.daos.DAO#delete(java.io.Serializable[])
*/
publicvoiddelete(Serializable... entityids)
{
for(Object id : entityids)
{
super.getHibernateTemplate().delete(find((Serializable) id));
}
}
/*
* @see org.usc.daos.DAO#find(java.io.Serializable)
*/
publicT find(Serializable entityId)
{
if(null!= entityId)
return(T)super.getHibernateTemplate().get(entityClass, entityId);
returnnull;
}
/*
* @see org.usc.daos.DAO#getCount()
*/
publicintgetCount()
{
String hql ="select count( "+keyFieldName+") from "+entityClassName;
intcount = Integer.parseInt(super.getHibernateTemplate().find(hql).get(0).toString());
returncount;
}
publicvoidsave(Object entity)
{
super.getHibernateTemplate().save(entity);
}
/*
* @see org.usc.daos.DAO#update(java.lang.Object)
*/
publicvoidupdate(Object entity)
{
super.getHibernateTemplate().update(entity);
}
/*
* @see org.usc.daos.DAO#getScrollData(int, int, java.lang.String, java.lang.Object[], java.util.LinkedHashMap)
*/
publicQueryResult getScrollData(finalintfirstindex,finalintmaxresult,finalString wherejpql,finalObject[] queryParams,
finalLinkedHashMap orderby)
{
finalQueryResult queryResult =newQueryResult();
super.getHibernateTemplate().execute(newHibernateCallback()
{
publicT doInHibernate(Session session)throwsHibernateException, SQLException
{
String hql ="from "+entityClassName+" o "+ (wherejpql ==null||"".equals(wherejpql.trim()) ?"":" where "+ wherejpql)
+ buildOrderby(orderby);
Query query = session.createQuery(hql);
setQueryParams(query, queryParams);// where
queryResult.setTotalRecord(query.list().size());// first get size
if(firstindex != -1 && maxresult != -1)
query.setFirstResult(firstindex).setMaxResults(maxresult);// last page
queryResult.setResultList(query.list());
returnnull;
}
});
returnqueryResult;
}
/*
* @see org.usc.daos.DAO#getScrollData(int, int, java.lang.String, java.lang.Object[])
*/
publicQueryResult getScrollData(intfirstindex,intmaxresult, String wherejpql, Object[] queryParams)
{
returngetScrollData(firstindex, maxresult, wherejpql, queryParams,null);
}
/*
* @see org.usc.daos.DAO#getScrollData(int, int, java.util.LinkedHashMap)
*/
publicQueryResult getScrollData(finalintfirstindex,finalintmaxresult,finalLinkedHashMap orderby)
{
returngetScrollData(firstindex, maxresult,null,null, orderby);
}
/*
* @see org.usc.daos.DAO#getScrollData(int, int)
*/
publicQueryResult getScrollData(finalintfirstindex,finalintmaxresult)
{
returngetScrollData(firstindex, maxresult,null,null,null);
}
/*
* @see org.usc.daos.DAO#getScrollData()
*/
publicQueryResult getScrollData()
{
returngetScrollData(-1, -1,null,null,null);
}
/*
* @see org.usc.daos.DAO#save(java.lang.Object)
*/
/**
*获取实体的名称
*
*@param
*@paramclazz
*实体类
*@return
*/
protectedstatic String getEntityName(Class clazz)
{
String entityname = clazz.getSimpleName();
Entityentity = clazz.getAnnotation(Entity.class);
if(entity.name() !=null&& !"".equals(entity.name()))
{
entityname = entity.name();
}
returnentityname;
}
/**
*获取实体的主键
*
*@param
*@paramclazz
*实体类
*@return主键名
*/
protectedstatic String getKeyFieldName(Class clazz)
{
try
{
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
for(PropertyDescriptor propertydesc : propertyDescriptors)
{
Method method = propertydesc.getReadMethod();
if(null!= method &&null!= method.getAnnotation(javax.persistence.Id.class))
{
returnpropertydesc.getName();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return"id";
}
/**
*设置HQL里边的属性值
*
*@paramquery
*@paramqueryParams
*/
protectedstaticvoidsetQueryParams(Query query, Object[] queryParams)
{
if(queryParams !=null&& queryParams.length> 0)
{
for(inti = 0; i < queryParams.length; i++)
{
query.setParameter(i, queryParams[i]);//从0开始
}
}
}
/**
*组装order by语句
*
*@paramorderby
*@return
*/
protectedstaticString buildOrderby(LinkedHashMap orderby)
{
StringBuffer orderbyql =newStringBuffer("");
if(orderby !=null&& orderby.size() > 0)
{
orderbyql.append(" order by ");
for(String key : orderby.keySet())
{
orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");
}
orderbyql.deleteCharAt(orderbyql.length() - 1);
}
returnorderbyql.toString();
}
protectedstatic String getCountField(Class clazz)
{
String out ="o";
try
{
PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
for(PropertyDescriptor propertydesc : propertyDescriptors)
{
Method method = propertydesc.getReadMethod();
if(method !=null&& method.isAnnotationPresent(EmbeddedId.class))
{
PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType()).getPropertyDescriptors();
out ="o."+ propertydesc.getName() +"."+ (!ps[1].getName().equals("class") ? ps[1].getName() : ps[0].getName());
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
returnout;
}
}