项目使用的hibernate基于hibernate3.5和spring3.0.5
package com.juttec.core.dao;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.support.DaoSupport;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.util.Assert;
import com.juttec.common.util.XLogger;
import com.juttec.core.exception.InvalidDataException;
import com.juttec.core.exception.InvalidParamException;
public abstract class HibernateDao<T, PK extends Serializable> extends DaoSupport
{
private Class<T> entityClass;
private SessionFactory sessionFactory = null;
private HibernateTemplate hibernateTemplate;
public Class<T> getEntityClass()
{
return this.entityClass;
}
private SessionFactory getSessionFactory()
{
if (this.sessionFactory != null) return this.sessionFactory;
if (getHibernateTemplate() != null) {
return getHibernateTemplate().getSessionFactory();
}
return null;
}
public void setSessionFactory(SessionFactory sessFactory)
{
this.sessionFactory = sessFactory;
if ((getHibernateTemplate() == null) || (sessFactory != getHibernateTemplate().getSessionFactory()))
{
HibernateTemplate hibTemplate = createHibernateTemplate(sessFactory);
setHibernateTemplate(hibTemplate);
}
}
public HibernateDao()
{
this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
}
protected final void checkDaoConfig()
{
if (getHibernateTemplate() == null)
throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required");
}
public void update(T entity)
{
Assert.notNull(entity, "entity不能为空");
getHibernateTemplate().update(entity);
this.logger.debug("update entity:" + entity);
}
public void flush()
{
getHibernateTemplate().flush();
}
public void clear()
{
getHibernateTemplate().clear();
}
public void save(T entity) {
Assert.notNull(entity, "entity不能为空");
getHibernateTemplate().save(entity);
this.logger.debug("saveObj entity: " + entity);
}
public void saveOrUpdate(T entity)
{
Assert.notNull(entity, "entity不能为空");
getHibernateTemplate().saveOrUpdate(entity);
this.logger.debug("save entity: {}" + entity);
}
public void delete(T entity)
{
Assert.notNull(entity, "entity不能为空");
getHibernateTemplate().delete(entity);
this.logger.debug("delete entity:" + entity);
}
public void delete(PK id)
{
Assert.notNull(id, "id不能为空");
delete(get(id));
this.logger.debug("delete entity:" + this.entityClass.getSimpleName() + ", id:" + id);
}
public T get(PK id)
{
try
{
Assert.notNull(id, "id不能为空");
} catch (AssertionError e) {
return null;
}
Object o = getHibernateTemplate().get(this.entityClass, id);
if (o == null) return null;
return (T) o;
}
public T load(PK id)
{
try
{
Assert.notNull(id, "id不能为空");
} catch (AssertionError e) {
return null;
}
Object o = getHibernateTemplate().load(this.entityClass, id);
if (o == null) return null;
return (T) o;
}
// public List<T> get(Collection<PK> ids)
// {
// return find(new Criterion[] { Restrictions.in(getIdName(), ids) });
// }
public Object merge(T t)
{
if (t == null) return null;
return getHibernateTemplate().merge(t);
}
public List<T> getAllObjects()
{
return getAllObjects("", true);
}
public List<T> getAllObjects(String orderByProperty, boolean isAsc)
{
String hql = "from " + getEntityClass().getName();
if (orderByProperty.length() > 0) {
hql = hql + " order by " + orderByProperty;
if (isAsc)
hql = hql + " ASC";
else {
hql = hql + " DESC";
}
}
return retrieve(hql);
}
public List<T> findBy(String properName, Object propValue)
{
Assert.hasText(properName, "properName不能为空");
String hql = "from " + getEntityClass().getName() + " where " + properName + " = :val";
List results = getHibernateTemplate().findByNamedParam(hql, "val", propValue);
return results;
}
public T findUniqueResult(String properName, Object propValue)
{
Assert.hasText(properName, "propertyName不能为空");
String hql = "from " + getEntityClass().getName() + " where " + properName + " = :val";
List results = getHibernateTemplate().findByNamedParam(hql, "val", propValue);
if (results == null) {
return null;
}
if (results.size() > 0) {
return (T) results.get(0);
}
return null;
}
public <X> List<X> find(String hql, Object[] values)
{
return getHibernateTemplate().find(hql, values);
}
public <X> List<X> find(String hql, Map<String, ?> keyValueMap)
{
if (keyValueMap == null) {
return find(hql, new Object[0]);
}
Object[] keyObjs = keyValueMap.keySet().toArray();
String[] keys = new String[keyValueMap.size()];
Object[] values = new Object[keyValueMap.size()];
int i = 0;
for (Object key : keyObjs) {
keys[i] = ((String)key);
values[i] = keyValueMap.get((String)key);
i++;
}
return getHibernateTemplate().findByNamedParam(hql, keys, values);
}
public <X> X findUniqueResult(String hql, Object[] values)
{
List results = find(hql, values);
if (results == null) {
return null;
}
if (results.size() > 0) {
return (X) results.get(0);
}
return null;
}
public <X> X findUnique(String hql, Map<String, ?> valueMap)
{
List results = find(hql, valueMap);
if (results == null) {
return null;
}
if (results.size() > 0) {
return (X) results.get(0);
}
return null;
}
/**
*
* 执行sql更新
* <pre>
* 执行sql更新
* </pre>
*
* @author 李晓东
* @param sql
*/
public void execSqlUpdate(String sql) throws Exception {
getSession().createSQLQuery(sql).executeUpdate();
}
@SuppressWarnings("unchecked")
public int execUpdate(final String hql, final Object[] values)
{
Integer result = (Integer)getHibernateTemplate().executeWithNativeSession(
new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = session.createQuery(hql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return Integer.valueOf(query.executeUpdate());
}
});
return result.intValue();
}
public int execUpdate(final String hql, final Map<String, ?> values)
{
Integer result = (Integer)getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = HibernateDao.this.createQuery(session, hql, values);
return Integer.valueOf(query.executeUpdate());
}
});
return result.intValue();
}
/** @deprecated */
public Query createQuery(String queryString, Object[] values)
{
Assert.hasText(queryString, "queryString不能为空");
Query query = getSession().createQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}
/** @deprecated */
public Query createQuery(String queryString, Map values)
{
Assert.hasText(queryString, "queryString不能为空");
Query query = getSession().createQuery(queryString);
if(values != null)
query.setProperties(values);
return query;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,带分页功能(参数为数组格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > sqlQuery(final String queryString, final Object[] values, final int offset, final int limit, String countName, String rowsName)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
@SuppressWarnings("unchecked")
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
@SuppressWarnings("unchecked")
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
String countSql = "select count(0) from(" + queryString +") tbc";
SQLQuery query = session.createSQLQuery(countSql);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,带分页功能(参数为数组格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > sqlQuery(final String queryString, final String countQuery, final int offset, final int limit, String countName, String rowsName, final Object... values)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
@SuppressWarnings("unchecked")
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
@SuppressWarnings("unchecked")
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(countQuery);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > sqlQuery(final String queryString, final Map<String, ?> values, final int offset, final int limit, String countName, String rowsName)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
query.setProperties(values);
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
//查询总数
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
String countSql = "select count(0) from(" + queryString +") tbc";
SQLQuery query = session.createSQLQuery(countSql);
if (values != null) {
query.setProperties(values);
}
// query.setResultTransformer(Transformers.aliasToBean(getEntityClass()));
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > sqlQuery(final String queryString, final String countQuery, final Map<String, ?> values, final int offset, final int limit, String countName, String rowsName)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
query.setProperties(values);
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
//查询总数
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(countQuery);
if (values != null) {
query.setProperties(values);
}
// query.setResultTransformer(Transformers.aliasToBean(getEntityClass()));
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,不带分页功能(参数为数组格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public List sqlQuery(final String queryString, final Object... values)
{
Assert.hasText(queryString, "queryString不能为空");
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
return query.list();
}
});
return (List)results;
}
/**
*
* sql的查询方式.
* <pre>
* sql的查询方式,不带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public List sqlQuery(final String queryString, final Map<String, ?> values)
{
Assert.hasText(queryString, "queryString不能为空");
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
SQLQuery query = session.createSQLQuery(queryString);
if (values != null) {
query.setProperties(values);
}
query.setResultTransformer(new BeanTransformerAdapter(getEntityClass()));
return query.list();
}
});
return (List)results;
}
// public List sqlQuery(final String queryString, final Map<String, Type> scalarMap, final Map<String, ?> values)
// {
// Assert.hasText(queryString, "queryString不能为空");
//
// Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
// public Object doInHibernate(Session session) {
// SQLQuery query = session.createSQLQuery(queryString);
// if (values != null) {
// query.setProperties(values);
// }
//
// if (scalarMap != null) {
// Set keys = scalarMap.keySet();
// for (Object key : keys) {
// query.addScalar((String) key, (Type)scalarMap.get(key));
// }
// }
//
// return query.list();
// }
// });
// return (List)results;
// }
//
// public List sqlQuery(final String queryString, final Map<String, Type> scalarMap, final Object[] values)
// {
// Assert.hasText(queryString, "queryString不能为空");
//
// Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
// public Object doInHibernate(Session session) {
// SQLQuery query = session.createSQLQuery(queryString);
// if (values != null) {
// for (int i = 0; i < values.length; i++) {
// query.setParameter(i, values[i]);
// }
//
// }
//
// if (scalarMap != null) {
// Set keys = scalarMap.keySet();
// for (Object key : keys) {
// query.addScalar((String) key, (Type)scalarMap.get(key));
// }
// }
//
// return query.list();
// }
// });
// return (List)results;
// }
/** @deprecated */
public SQLQuery createSqlQuery(String queryString, Object[] values)
{
Assert.hasText(queryString, "queryString不能为空");
SQLQuery query = getSession().createSQLQuery(queryString);
if (values != null) {
for (int i = 0; i < values.length; i++) {
query.setParameter(i, values[i]);
}
}
return query;
}
/** @deprecated */
public SQLQuery createSqlQuery(String queryString, Map<String, ?> values)
{
Assert.hasText(queryString, "queryString不能为空");
SQLQuery query = getSession().createSQLQuery(queryString);
if (values != null) {
query.setProperties(values);
}
return query;
}
/** @deprecated */
public Object getObject(Class clazz, Serializable idVal)
{
return getHibernateTemplate().get(clazz, idVal);
}
/**
*
* hql查询方法,不带分页功能.
* <pre>
* hql查询方法,不带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public List retrieve(final String queryString, final Map<String, ?> values)
{
Assert.hasText(queryString, "queryString不能为空");
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = session.createQuery(queryString);
if (values != null) {
query.setProperties(values);
}
return query.list();
}
});
return (List)results;
}
/**
*
* hql查询方法,带分页功能.
* <pre>
* hql查询方法,带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > retrieve(final String queryString, final Map<String, ?> values, final int offset, final int limit, String countName, String rowsName)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = session.createQuery(queryString);
if (values != null) {
query.setProperties(values);
}
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
String hql = "select count(id) " + queryString;
Query query = session.createQuery(hql);
if (values != null) {
query.setProperties(values);
}
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
/**
*
* hql查询方法,带分页功能.
* <pre>
* hql查询方法,带分页功能(参数为map格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param values
* @return
*/
public HashMap < String , Object > retrieve(final String queryString, final String countQuery, final Map<String, ?> values, final int offset, final int limit, String countName, String rowsName)
{
Assert.hasText(queryString, "queryString不能为空");
HashMap < String , Object > map = new HashMap < String , Object >();
Object results = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
Query query = session.createQuery(queryString);
if (values != null) {
query.setProperties(values);
}
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.list();
}
});
Object resultsCount = getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
// String hql = "select count(id) " + queryString;
Query query = session.createQuery(countQuery);
if (values != null) {
query.setProperties(values);
}
return (Number)query.uniqueResult();
}
});
map.put(countName, resultsCount);
map.put(rowsName, (List)results);
return map;
}
public Object retrieveFirst(String queryString, Map<String, ?> values)
{
List results = retrieve(queryString, values);
if ((results == null) || (results.size() == 0)) {
return null;
}
return results.get(0);
}
public Object retrieveFirst(String queryString, Object... propValues)
{
List results = retrieve(queryString, propValues);
if ((results == null) || (results.size() == 0)) {
return null;
}
return results.get(0);
}
public List<T> find(final Criterion[] criterions)
{
List result = (List)getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session) {
Criteria criteria = session.createCriteria(HibernateDao.this.entityClass);
for (Criterion c : criterions) {
criteria.add(c);
}
return criteria.list();
}
});
return result;
}
public T findUnique(Criterion[] criterions)
{
List results = find(criterions);
if (results == null)
return null;
if (results.size() > 0) {
return (T) results.get(0);
}
return null;
}
public List<T> findByNamedParam(String queryString, String paramName, Object value)
{
return getHibernateTemplate().findByNamedParam(queryString, paramName, value);
}
public List<T> findByNamedParam(String queryString, String[] paramNames, Object[] values)
{
return getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
}
public T findFirstByNamedParam(String queryString, String paramName, Object value)
{
List list = getHibernateTemplate().findByNamedParam(queryString, paramName, value);
if ((list != null) && (list.size() > 0)) return (T) list.get(0);
return null;
}
public T findFirstByNamedParam(String queryString, String[] paramNames, Object[] values)
{
List list = getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
if ((list != null) && (list.size() > 0)) return (T) list.get(0);
return null;
}
public List<T> findByPropValues(String[] searchedProps, Object[] propValues)
{
if ((searchedProps == null) || (searchedProps.length == 0)) {
throw new InvalidParamException("searchedProps");
}
if ((propValues == null) || (propValues.length == 0)) throw new InvalidParamException("propValues");
if (searchedProps.length != propValues.length) {
throw new InvalidDataException("参数数组长度不一致:searchedProps:" + searchedProps.length + ", propValues:" + propValues.length);
}
String hql = "from " + getEntityClass().getName();
if (searchedProps.length > 0) {
hql = hql + " where ";
String filter = "";
for (String prop : searchedProps) {
if (filter.length() > 0) filter = filter + " or ";
filter = filter + prop + " = ?";
}
hql = hql + "(" + filter + ")";
}
return getHibernateTemplate().find(hql, propValues);
}
public void initProxyObject(Object proxy)
{
Hibernate.initialize(proxy);
}
public Query distinct(Query query)
{
query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return query;
}
public Criteria distinct(Criteria criteria)
{
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
return criteria;
}
public String getIdName()
{
ClassMetadata meta = getSessionFactory().getClassMetadata(this.entityClass);
return meta.getIdentifierPropertyName();
}
public boolean isPropertyUnique(String propertyName, Object newValue, Object oldValue)
{
if ((newValue == null) || (newValue.equals(oldValue))) {
return true;
}
Object object = findUniqueResult(propertyName, newValue);
return object == null;
}
protected HibernateTemplate createHibernateTemplate(SessionFactory sessFactory)
{
return new HibernateTemplate(sessFactory);
}
public HibernateTemplate getHibernateTemplate()
{
return this.hibernateTemplate;
}
public void setHibernateTemplate(HibernateTemplate hibTemplate)
{
this.hibernateTemplate = hibTemplate;
}
public Session getSession()
{
return getSession(this.hibernateTemplate.isAllowCreate());
}
protected final Session getSession(boolean allowCreate) {
if (!allowCreate) {
return SessionFactoryUtils.getSession(getSessionFactory(), false);
}
return SessionFactoryUtils.getSession(getSessionFactory(), getHibernateTemplate().getEntityInterceptor(), getHibernateTemplate().getJdbcExceptionTranslator());
}
public final void releaseSession(Session session)
{
SessionFactoryUtils.releaseSession(session, getSessionFactory());
}
protected final DataAccessException convertHibernateAccessException(HibernateException ex) {
return getHibernateTemplate().convertHibernateAccessException(ex);
}
public List retrieve(String queryString)
{
return getHibernateTemplate().find(queryString);
}
/**
*
* hql查询方法,不带分页功能.
* <pre>
* hql查询方法,不带分页功能(参数为数组格式)
* </pre>
*
* @author 杨雷
* @param queryString
* @param propValues
* @return
*/
public List retrieve(String queryString, Object... propValues)
{
return getHibernateTemplate().find(queryString, propValues);
}
private String prepareCountHql(String orgHql) {
String fromHql = orgHql;
fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
fromHql = StringUtils.substringBefore(fromHql, "order by");
String countHql = "select count(*) " + fromHql;
return countHql;
}
private <X> X findUnique(Session session, String hql, Map<String, ?> values)
{
return (X) createQuery(session, hql, values).uniqueResult();
}
private Query createQuery(Session session, String queryString, Map<String, ?> values)
{
Assert.notNull(session, "session不能为空");
Assert.hasText(queryString, "queryString不能为空");
Query query = session.createQuery(queryString);
if (values != null) {
query.setProperties(values);
}
return query;
}
public int getObjectCount()
{
String hql = "select count(*) from " + getEntityClass().getName();
List results = retrieve(hql);
if ((results != null) && (results.size() > 0)) {
return ((Long)results.get(0)).intValue();
}
return 0;
}
public int getObjectCountByPropValue(String searchedProp, Object propValue)
{
return getObjectCountByPropValues(new String[] { searchedProp }, new Object[] { propValue });
}
public int getObjectCountByPropValues(String[] searchedProps, Object[] propValues)
{
if ((searchedProps == null) || (searchedProps.length == 0)) {
XLogger.getLogger().error("searchProps is empty.");
return 0;
}
if ((propValues == null) || (propValues.length == 0)) {
XLogger.getLogger().error("propValues is empty.");
return 0;
}
if (searchedProps.length != propValues.length) {
XLogger.getLogger().error("searchProps and propValues are not of the same length.");
return 0;
}
String hql = "select count(tAlias_) from " + getEntityClass().getName() + " tAlias_ ";
if (searchedProps.length > 0) {
hql = hql + " where ";
String filter = "";
for (String prop : searchedProps) {
if (filter.length() > 0) filter = filter + " or ";
filter = filter + prop + " = ?";
}
hql = hql + "(" + filter + ")";
}
List results = retrieve(hql, propValues);
if ((results == null) || (results.size() == 0)) {
return 0;
}
Long result = (Long)results.get(0);
if (result == null) {
return 0;
}
return result.intValue();
}
public HashMap < String , Object > findByHSQL ( final String hql ) throws Exception {
final HashMap < String , Object > map = new HashMap < String , Object >();
final List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate ( final Session session ) throws HibernateException , SQLException {
final Query query = session.createQuery(hql);
final List list = query.list();
return list;
}
});
map.put("items", list);
map.put("count", Integer.valueOf(list.size()).longValue());
return map;
}
public HashMap < String , Object > findBySQL ( final String hql ,
final Object ob ,
final int start ,
final int limit ) throws Exception {
final List list = getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate ( final Session session ) throws HibernateException , SQLException {
final SQLQuery query = session.createSQLQuery(hql);
if (ob != null)
{
query.addEntity(ob.getClass());
}
if (start >= 0)
{
query.setFirstResult(start);
}
if (limit > 0)
{
query.setMaxResults(limit);
}
final List list = query.list();
// Log.info(list.size());
return list;
}
});
final HashMap < String , Object > map = new HashMap < String , Object >();
map.put("items",
list);
map.put("count",
Integer.valueOf(list.size()).longValue());
return map;
}
}
ReflectionUtils.java
package com.juttec.core.dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.juttec.common.util.XLogger;
public class ReflectionUtils
{
public static Class getSuperClassGenricType(Class clazz)
{
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
XLogger.getLogger().warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType)genType).getActualTypeArguments();
if ((params == null) || (params.length == 0)) {
XLogger.getLogger().warn("params == null || params.length == 0 ");
return Object.class;
}
if (!(params[0] instanceof Class)) {
XLogger.getLogger().warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class)params[0];
}
}
BeanTransformerAdapter.java
package com.juttec.core.dao;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.StringUtils;
public class BeanTransformerAdapter<T> implements ResultTransformer {
private static final long serialVersionUID = 8149706114474043039L;
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());
/** The class we are mapping to */
private Class<T> mappedClass;
/** Whether we're strictly validating */
private boolean checkFullyPopulated = false;
/** Whether we're defaulting primitives when mapping a null value */
private boolean primitivesDefaultedForNullValue = false;
/** Map of the fields we provide mapping for */
private Map<String, PropertyDescriptor> mappedFields;
/** Set of bean properties we provide mapping for */
private Set<String> mappedProperties;
/**
* Create a new BeanPropertyRowMapper for bean-style configuration.
* @see #setMappedClass
* @see #setCheckFullyPopulated
*/
public BeanTransformerAdapter() {
}
/**
* Create a new BeanPropertyRowMapper, accepting unpopulated properties
* in the target bean.
* <p>Consider using the {@link #newInstance} factory method instead,
* which allows for specifying the mapped type once only.
* @param mappedClass the class that each row should be mapped to
*/
public BeanTransformerAdapter(Class<T> mappedClass) {
initialize(mappedClass);
}
/**
* Create a new BeanPropertyRowMapper.
* @param mappedClass the class that each row should be mapped to
* @param checkFullyPopulated whether we're strictly validating that
* all bean properties have been mapped from corresponding database fields
*/
public BeanTransformerAdapter(Class<T> mappedClass, boolean checkFullyPopulated) {
initialize(mappedClass);
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Set the class that each row should be mapped to.
*/
public void setMappedClass(Class<T> mappedClass) {
if (this.mappedClass == null) {
initialize(mappedClass);
} else {
if (!this.mappedClass.equals(mappedClass)) {
throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to "
+ mappedClass + " since it is already providing mapping for " + this.mappedClass);
}
}
}
/**
* Initialize the mapping metadata for the given class.
* @param mappedClass the mapped class.
*/
protected void initialize(Class<T> mappedClass) {
this.mappedClass = mappedClass;
this.mappedFields = new HashMap<String, PropertyDescriptor>();
this.mappedProperties = new HashSet<String>();
PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null) {
this.mappedFields.put(pd.getName().toLowerCase(), pd);
String underscoredName = underscoreName(pd.getName());
if (!pd.getName().toLowerCase().equals(underscoredName)) {
this.mappedFields.put(underscoredName, pd);
}
this.mappedProperties.add(pd.getName());
}
}
}
/**
* Convert a name in camelCase to an underscored name in lower case.
* Any upper case letters are converted to lower case with a preceding underscore.
* @param name the string containing original name
* @return the converted name
*/
private String underscoreName(String name) {
if (!StringUtils.hasLength(name)) {
return "";
}
StringBuilder result = new StringBuilder();
result.append(name.substring(0, 1).toLowerCase());
for (int i = 1; i < name.length(); i++) {
String s = name.substring(i, i + 1);
String slc = s.toLowerCase();
if (!s.equals(slc)) {
result.append("_").append(slc);
} else {
result.append(s);
}
}
return result.toString();
}
/**
* Get the class that we are mapping to.
*/
public final Class<T> getMappedClass() {
return this.mappedClass;
}
/**
* Set whether we're strictly validating that all bean properties have been
* mapped from corresponding database fields.
* <p>Default is {@code false}, accepting unpopulated properties in the
* target bean.
*/
public void setCheckFullyPopulated(boolean checkFullyPopulated) {
this.checkFullyPopulated = checkFullyPopulated;
}
/**
* Return whether we're strictly validating that all bean properties have been
* mapped from corresponding database fields.
*/
public boolean isCheckFullyPopulated() {
return this.checkFullyPopulated;
}
/**
* Set whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
* <p>Default is {@code false}, throwing an exception when nulls are mapped to Java primitives.
*/
public void setPrimitivesDefaultedForNullValue(boolean primitivesDefaultedForNullValue) {
this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue;
}
/**
* Return whether we're defaulting Java primitives in the case of mapping a null value
* from corresponding database fields.
*/
public boolean isPrimitivesDefaultedForNullValue() {
return primitivesDefaultedForNullValue;
}
/**
* Initialize the given BeanWrapper to be used for row mapping.
* To be called for each row.
* <p>The default implementation is empty. Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
}
/**
* Retrieve a JDBC object value for the specified column.
* <p>The default implementation calls
* {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}.
* Subclasses may override this to check specific value types upfront,
* or to post-process values return from {@code getResultSetValue}.
* @param rs is the ResultSet holding the data
* @param index is the column index
* @param pd the bean property that each result object is expected to match
* (or {@code null} if none specified)
* @return the Object value
* @throws SQLException in case of extraction failure
* @see org.springframework.jdbc.support.JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)
*/
protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
}
/**
* Static factory method to create a new BeanPropertyRowMapper
* (with the mapped class specified only once).
* @param mappedClass the class that each row should be mapped to
*/
public static <T> BeanPropertyRowMapper<T> newInstance(Class<T> mappedClass) {
BeanPropertyRowMapper<T> newInstance = new BeanPropertyRowMapper<T>();
newInstance.setMappedClass(mappedClass);
return newInstance;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
T mappedObject = BeanUtils.instantiate(this.mappedClass);
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
initBeanWrapper(bw);
Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);
for (int i = 0; i < aliases.length; i++) {
String column = aliases[i];
PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
if (pd != null) {
try {
Object value = tuple[i];
try {
bw.setPropertyValue(pd.getName(), value);
} catch (TypeMismatchException e) {
if (value == null && primitivesDefaultedForNullValue) {
logger.debug("Intercepted TypeMismatchException for column " + column + " and column '"
+ column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType()
+ " on object: " + mappedObject);
} else {
throw e;
}
}
if (populatedProperties != null) {
populatedProperties.add(pd.getName());
}
} catch (NotWritablePropertyException ex) {
throw new DataRetrievalFailureException("Unable to map column " + column
+ " to property " + pd.getName(), ex);
}
}
}
if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
+ "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
}
return mappedObject;
}
@Override
public List transformList(List list) {
return list;
}
}