import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Hibernate基本DAO功能的封装.
*
* @author
*/
public abstract class BaseHibernateDao<E, PK extends Serializable> extends HibernateDaoSupport implements EntityDao<E, PK> {
private Class<E> entityClass;
protected Logger logger = LoggerFactory.getLogger(getClass()); //NOSONAR
private static final int DEFAULT_MAX_RESULTS = 2000;
@SuppressWarnings("unchecked") //NOSONAR
public BaseHibernateDao() {
Class typeCls = getClass();
Type genType = typeCls.getGenericSuperclass();
while (true) {
if (!(genType instanceof ParameterizedType)) {
typeCls = typeCls.getSuperclass();
genType = typeCls.getGenericSuperclass();
} else {
break;
}
}
this.entityClass = (Class<E>) ((ParameterizedType) genType).getActualTypeArguments()[0];
}
public void initDao() {
if (getHibernateTemplate().getMaxResults() == 0) {
setMaxResults(DEFAULT_MAX_RESULTS);
// logger.debug("Setting default max results of DAO to " + getHibernateTemplate().getMaxResults());
}
}
/**
* 设置getHibernateTemplate方式使用时默认的最大返回条数.
*
* @param maxResults
*/
public void setMaxResults(int maxResults) {
getHibernateTemplate().setMaxResults(maxResults);
}
/**
* 获取getHibernateTemplate方式使用时默认的最大返回条数.
*
* @return maxResult
*/
public int getMaxResults() {
return getHibernateTemplate().getMaxResults();
}
//TODO use javacommon.util.extjs.ExtJsPageHelper
protected Page<E> pageQuery(int pageNumber, int pageSize, DetachedCriteria detachedCriteria) {
Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
int totalCount = (
(Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()
).intValue();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
//criteria = detachedCriteria.getExecutableCriteria(getSession());
List<E> items = criteria.setFirstResult(PageUtils.getFirstResult(pageNumber, pageSize)).setMaxResults(pageSize).list();
return new Page<E>(pageNumber, pageSize, totalCount, items);
}
protected Page<E> pageQuery(int pageNumber, int pageSize, DetachedCriteria detachedCriteria, Order[] orders) {
Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
int totalCount = (
(Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()
).intValue();
criteria.setProjection(null);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
//criteria = detachedCriteria.getExecutableCriteria(getSession());
for (Order order : orders) {
criteria.addOrder(order);
}
List<E> items = criteria.setFirstResult(PageUtils.getFirstResult(pageNumber, pageSize)).setMaxResults(pageSize).list();
return new Page<E>(pageNumber, pageSize, totalCount, items);
}
/**
* 查询数据表所有数据.
*
* @return List
*/
@SuppressWarnings("unchecked") //NOSONAR
public List<E> findAll() {
return getSession().createCriteria(getEntityClass()).list();
}
// /**
// * 查询数据表所有的数据并排序.
// * @param defaultOrders
// * @return List
// */
// @SuppressWarnings("unchecked") //NOSONAR
// @Deprecated
// public List<E> findAll(LinkedHashMap<String, Boolean> defaultOrders) {
// Criteria criteria = getSession().createCriteria(getEntityClass());
// if (defaultOrders != null && !defaultOrders.isEmpty()){
// for(Entry<String, Boolean> defaultOrder: defaultOrders.entrySet()){
// criteria.addOrder(defaultOrder.getValue() ? Order.asc(defaultOrder.getKey()) : Order.desc(defaultOrder.getKey()));
// }
// }
// return criteria.list();
// }
/**
* 查询数据表分页数据.
*
* @param start
* @param limit
* @return List<Object>
*/
@SuppressWarnings("unchecked") //NOSONAR
public List<E> findAllUsePageLimit(int start, int limit) {
Criteria criteria = getSession().createCriteria(getEntityClass());
criteria.setFirstResult(start);
criteria.setMaxResults(limit);
return criteria.list();
}
// /**
// * 查询数据表分页数据并排序.
// * @param defaultOrders
// * @param start
// * @param limit
// * @return List<Object>
// */
// @SuppressWarnings("unchecked") //NOSONAR
// public List<E> findAllUsePageLimit(LinkedHashMap<String, Boolean> defaultOrders, int start, int limit) {
// Criteria criteria = getSession().createCriteria(getEntityClass());
// if (defaultOrders != null && !defaultOrders.isEmpty())
// for(Entry<String, Boolean> defaultOrder: defaultOrders.entrySet())
// criteria.addOrder(defaultOrder.getValue() ? Order.asc(defaultOrder.getKey()) : Order.desc(defaultOrder.getKey()));
// criteria.setFirstResult(start);
// criteria.setMaxResults(limit);
// return criteria.list();
// }
/**
* 保存记录.
*
* @param obj
*/
public void save(E obj) {
getSession().save(obj);
}
/**
* 保存或修改记录.
*
* @param obj
*/
public void saveOrUpdate(E obj) {
getSession().saveOrUpdate(obj);
}
/**
* 修改记录.
*
* @param obj
*/
public void update(E obj) {
getSession().update(obj);
}
/**
* 删除记录.
*
* @param obj
*/
public void delete(E obj) {
getSession().delete(obj);
}
/**
* 刷新记录.
*
* @param obj
*/
public void refresh(BaseEntity obj) {
getSession().refresh(obj);
}
/**
* 按照实例构建一个条件查询,实例NULL的属性将被排除条件
*
* @param obj
*/
public List<E> findByExample(E obj) {
return getSession()
.createCriteria(this.getEntityClass())
.add(Example.create(obj))
.list();
}
/**
* 按照实例构建一个条件查询,实例NULL的属性将被排除条件
*
* @param obj
*/
public E getByExample(E obj) {
List<?> list = getSession()
.createCriteria(this.getEntityClass())
.add(Example.create(obj))
.list();
return list.size() == 0 ? null : (E) list.get(0);
}
/**
* 使用数据库的update严格的更新,解决update对象生成脏数据的问题.
*
* @param fieldsMap
* @param conditionMap
* @return 影响的记录条数
*/
public int strictUpdate(Map<String, Object> fieldsMap, Map<String, Object> conditionMap) {
if (fieldsMap.isEmpty()) {
return 0;
}
StringBuilder sqlBuilder = new StringBuilder("update " + this.getEntityClass().getSimpleName() + " set ");
int i = 0;
for (String fieldName : fieldsMap.keySet()) {
if (i > 0) {
sqlBuilder.append(", ");
}
sqlBuilder.append(fieldName + " = :" + fieldName);
i++;
}
sqlBuilder.append(" where ");
i = 0;
for (String fieldName : conditionMap.keySet()) {
if (i > 0) {
sqlBuilder.append(" and ");
}
sqlBuilder.append(fieldName + " = :" + fieldName);
i++;
}
HashMap<String, Object> sqlParamMap = new HashMap<String, Object>();
sqlParamMap.putAll(fieldsMap);
sqlParamMap.putAll(conditionMap);
Query query = getSession().createQuery(sqlBuilder.toString());
for (Entry<String, Object> entry : sqlParamMap.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
return query.executeUpdate();
}
/**
* 根据hibernate OID取记录.
*
* @param id
* @return Object
*/
@SuppressWarnings("unchecked") //NOSONAR
public E getById(PK id) {
return (E) getSession().get(getEntityClass(), id);
}
public void deleteById(PK id) {
E obj = getById(id);
if (obj != null) {
getSession().delete(obj);
}
}
/**
* 判断对象某些属性的值在数据库中是否唯一.
*
* @param uniquePropertyNames 在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password"
*/
public boolean isUnique(E entity, String[] uniquePropertyNames) {
// TODO implement it
return false;
}
public void flush() {
getHibernateTemplate().flush();
}
protected Class<E> getEntityClass() {
return entityClass;
}
}
Hibernate基本DAO功能的封装
最新推荐文章于 2022-12-05 08:28:19 发布