import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.reptile.basic.framework.dao.IBaseDao;
import com.reptile.basic.framework.model.QueryResult;
/**
* @Title: BaseDaoImpl
* @Description: dao接口实现公共类
* @author Bert
* @date 2011-8-9 上午09:43:54
* @version V1.0
*/
@SuppressWarnings("unchecked")
public class BaseDaoImpl implements IBaseDao {
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
private SessionFactory sessionFactory;
private Class persistentClass;
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
public BaseDaoImpl() {
if (persistentClass == null) {
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
this.persistentClass = (Class) pt.getActualTypeArguments()[0];
}
}
@Override
public void clear() {
this.getSession().flush();
this.getSession().clear();
}
@Override
public T save(T entity) {
this.getSession().save(entity);
return entity;
}
@Override
public void delete(T entity) {
this.getSession().delete(entity);
}
@Override
public T deleteById(Serializable id) {
T entity = load(id);
this.getSession().delete(entity);
return entity;
}
@Override
public void deleteByIds(Serializable... ids) {
if (ids != null && ids.length > 0) {
for (Serializable id : ids) {
Object entity = this.getSession().get(persistentClass, id);
if (entity != null) {
this.getSession().delete(entity);
} else {
throw new RuntimeException("您要查找的[" + id + "]不能为空!");
}
}
}
}
@Override
public T update(T entity) {
this.getSession().update(entity);
return entity;
}
@Override
public T saveOrUpdate(T entity) {
this.getSession().saveOrUpdate(entity);
return entity;
}
@Override
public T merge(T entity) {
return (T) this.getSession().merge(entity);
}
@Override
public void refresh(T entity) {
this.getSession().refresh(entity);
}
@Override
public T get(Serializable id) {
if (id != null) {
return (T) this.getSession().get(persistentClass, id);
} else {
//throw new RuntimeException("您要查找的[" + id + "]不能为空!");
return null;
}
}
@Override
public T get(String hql, Map params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
List l = query.list();
if (l != null && l.size() > 0) {
return l.get(0);
}
return null;
}
@Override
public T load(Serializable id) {
return (T) this.getSession().load(persistentClass, id);
}
@Override
public List getByIds(Serializable... ids) {
// return this.getSession().createQuery("from "+persistentClass+" where id in (:pks)").setParameterList("pks", pks).list();
return this.getSession().createCriteria(persistentClass).add(Restrictions.in("id", ids)).list();
}
@Override
public List findAll() {
// return this.getSession().createQuery("from "+persistentClass).list();
return this.getSession().createCriteria(persistentClass).list();
}
@Override
public long getCount() {
return (Long) this.getSession().createQuery("select count(" + getCountField(this.persistentClass) + ") from " + getEntityName(persistentClass) + " o").uniqueResult();
}
@Override
public long getCount(String whereJPQL, Map params) {
String entityName = getEntityName(this.persistentClass);
String where = (whereJPQL != null && !"".equals(whereJPQL.trim())) ? "where " + whereJPQL : "";
Query query = this.getSession().createQuery("select count(" + getCountField(this.persistentClass) + ") from " + entityName + " o " + where);
setParameters(query, params);
// 使用查询缓存,必须加该行代码
// query.setCacheable(true);
return (Long) query.uniqueResult();
}
public QueryResult getScrollData(int startIndex, int maxResult, String whereJPQL, Map params, LinkedHashMap orderby) {
QueryResult qr = new QueryResult();
String entityName = getEntityName(this.persistentClass);
String where = (whereJPQL != null && !"".equals(whereJPQL.trim())) ? "where " + whereJPQL : "";
Query query = this.getSession().createQuery("select o from " + entityName + " o " + where + buildOrderBy(orderby));
setParameters(query, params);
if (startIndex != -1 && maxResult != -1) {
query.setFirstResult(startIndex).setMaxResults(maxResult);
}
qr.setResultlist((List) query.list());// query.list();
if (startIndex != -1 && maxResult != -1) {
query = this.getSession().createQuery("select count(" + getCountField(this.persistentClass) + ") from " + entityName + " o " + where);
setParameters(query, params);
qr.setTotalrecord((Long) query.uniqueResult());
}
return qr;
}
/*
* @Override public QueryResult getScrollData(int startIndex, int maxResult, String whereJPQL, Object[] params, LinkedHashMap orderby) { QueryResult qr = new QueryResult(); String entityName = getEntityName(this.persistentClass); String where = (whereJPQL != null && !"".equals(whereJPQL.trim())) ? "where " + whereJPQL : ""; Query query = this.getSession().createQuery("select o from " + entityName + " o " + where + buildOrderBy(orderby)); setParameters(query, params); if (startIndex != -1 && maxResult != -1) { query.setFirstResult(startIndex).setMaxResults(maxResult); } qr.setResultlist((List) query.list());// query.list(); if (startIndex != -1 && maxResult != -1) { query = this.getSession().createQuery("select count(" + getCountField(this.persistentClass) + ") from " + entityName + " o " + where); setParameters(query, params); qr.setTotalrecord((Long) query.uniqueResult()); } return qr; }
*/
@Override
public QueryResult getScrollData(int startIndex, int maxResult, String whereJPQL, Map params) {
return getScrollData(startIndex, maxResult, whereJPQL, params, null);
}
@Override
public QueryResult getScrollData(int startIndex, int maxResult, LinkedHashMap orderby) {
return getScrollData(startIndex, maxResult, null, null, orderby);
}
@Override
public QueryResult getScrollData(int startIndex, int maxResult) {
return getScrollData(startIndex, maxResult, null, null, null);
}
@Override
public QueryResult getScrollData() {
return getScrollData(-1, -1, null, null, null);
}
@Override
public Integer executeHql(String hql){
Query query = this.getSession().createQuery(hql);
return query.executeUpdate();
}
@Override
public Integer executeHql(String hql,Map params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.executeUpdate();
}
@Override
public List executeHqlList(String hql){
Query query = this.getSession().createQuery(hql);
return query.list();
}
@Override
public List executeHqlList(String hql,Map params){
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.list();
}
/**
* @Title: getEntityName
* @Description: 获取实体名称
* @param entityClass
* @return
*/
private static String getEntityName(Class entityClass) {
String entityName = entityClass.getSimpleName();
Entity entity = entityClass.getAnnotation(Entity.class);
if (entity.name() != null && !"".equals(entity.name())) {
entityName = entity.name();
}
return entityName;
}
/**
* @Title: setParameters
* @Description: 设置hql语句需要的参数
* @param entityClass
* @return
*/
private static void setParameters(Query query, Map params) {
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
query.setParameter(key, params.get(key));
}
}
}
/**
* @Title: buildOrderBy
* @Description: 组织排序条件
* @param orderby
* : orderby.put("id", "asc"); orderby.put("name", "desc");
* @return
*/
private static String buildOrderBy(LinkedHashMap orderby) {
StringBuilder sb = new StringBuilder();
if (orderby != null && !orderby.isEmpty()) {
sb.append(" order by ");
for (String key : orderby.keySet()) {
sb.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* @Title: getCountField
* @Description: 获取主键
* @param clazz
* @return
*/
private static 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();
}
return out;
}
}