dao接口实现公共类
2014-02-11 13:30
232 查看
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<T extends Serializable> implements IBaseDao<T> {
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
private SessionFactory sessionFactory;
private Class<T> 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<T>) 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<String, Object> params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
List<T> 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<T> 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<T> 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<String, Object> 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Map<String, Object> params, LinkedHashMap<String, String> orderby) {
QueryResult<T> qr = new QueryResult<T>();
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<T>) 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Object[] params, LinkedHashMap<String, String> orderby) { QueryResult<T> qr = new QueryResult<T>(); 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<T>) 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Map<String, Object> params) {
return getScrollData(startIndex, maxResult, whereJPQL, params, null);
}
@Override
public QueryResult<T> getScrollData(int startIndex, int maxResult, LinkedHashMap<String, String> orderby) {
return getScrollData(startIndex, maxResult, null, null, orderby);
}
@Override
public QueryResult<T> getScrollData(int startIndex, int maxResult) {
return getScrollData(startIndex, maxResult, null, null, null);
}
@Override
public QueryResult<T> 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<String, Object> params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.executeUpdate();
}
@Override
public List<T> executeHqlList(String hql){
Query query = this.getSession().createQuery(hql);
return query.list();
}
@Override
public List<T> executeHqlList(String hql,Map<String, Object> params){
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.list();
}
/**
* @Title: getEntityName
* @Description: 获取实体名称
* @param entityClass
* @return
*/
private static <E> String getEntityName(Class<E> 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<String, Object> 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<String, String> 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 <E> String getCountField(Class<E> 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;
}
}
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<T extends Serializable> implements IBaseDao<T> {
private static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
private SessionFactory sessionFactory;
private Class<T> 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<T>) 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<String, Object> params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
List<T> 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<T> 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<T> 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<String, Object> 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Map<String, Object> params, LinkedHashMap<String, String> orderby) {
QueryResult<T> qr = new QueryResult<T>();
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<T>) 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Object[] params, LinkedHashMap<String, String> orderby) { QueryResult<T> qr = new QueryResult<T>(); 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<T>) 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<T> getScrollData(int startIndex, int maxResult, String whereJPQL, Map<String, Object> params) {
return getScrollData(startIndex, maxResult, whereJPQL, params, null);
}
@Override
public QueryResult<T> getScrollData(int startIndex, int maxResult, LinkedHashMap<String, String> orderby) {
return getScrollData(startIndex, maxResult, null, null, orderby);
}
@Override
public QueryResult<T> getScrollData(int startIndex, int maxResult) {
return getScrollData(startIndex, maxResult, null, null, null);
}
@Override
public QueryResult<T> 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<String, Object> params) {
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.executeUpdate();
}
@Override
public List<T> executeHqlList(String hql){
Query query = this.getSession().createQuery(hql);
return query.list();
}
@Override
public List<T> executeHqlList(String hql,Map<String, Object> params){
Query query = this.getSession().createQuery(hql);
setParameters(query, params);
return query.list();
}
/**
* @Title: getEntityName
* @Description: 获取实体名称
* @param entityClass
* @return
*/
private static <E> String getEntityName(Class<E> 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<String, Object> 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<String, String> 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 <E> String getCountField(Class<E> 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;
}
}
相关文章推荐
- Mybatis使用Mapper代理的方式生成DAO接口的实现类对象
- 解析SOA十大设计原则 公共接口与内部实现要明确界限
- DAO,Service接口与实现类设计
- zTree实现地市县三级级联DAO接口实现
- jdbc,数据库案例:客户信息管理系统:jsp部分,数据库数据封装类,dao接口和实现
- 如何整合Spring和Mybatis的思路分析(使用面向接口的mapper代理,不用再去写Dao的实现类)
- dao设计(四),预留实现(接口作为参数)
- C#找出接口的所有实现类并遍历执行这些类的公共方法
- 一个通用的DAO接口及其Hibernate3实现
- zTree市县实现三个梯级DAO接口测试
- Mybatis Mapper动态代理方法 即 只写Dao接口 不谢Dao的实现类
- JAVA通用Dao接口和hibernate的实现
- zTree实现地市县三级级联DAO接口实现
- mybatis源码学习--spring+mybatis注解方式为什么mybatis的dao接口不需要实现类
- (原创)c#学习笔记10--定义类成员03--接口的实现02--用非公共的可访问性添加属性存取器
- zTree实现地市县三级级联DAO接口实现
- SSH向Dao接口的实现类中用注解和声明方式注入创建HibernateTemplate对象
- 设计技巧9:内部类利用外部类方法实现公共接口 封装实现细节
- 一个通用的DAO接口及其Hibernate3实现 (2)