package cn.yisi.service.base;
import java.io.Serializable;
import java.util.LinkedHashMap;
import cn.yisi.bean.QueryResult;
public interface DAO<T> {
/**
*
* @param id 值
* @param colName 列名
* @return
*/
public T getByID(String id,String colName);
/**
* 获取记录总数
* @param entityClass 实体类
* @return
*/
public long getCount();
/**
* 清除一级缓存的数据
*/
public void clear();
/**
* 保存实体
* @param entity 实体id
*/
public void save(T entity);
/**
* 更新实体
* @param entity 实体id
*/
public void update(T entity);
/**
* 删除实体
* @param entityClass 实体类
* @param entityids 实体id数组
*/
public void delete(Serializable ... entityids);
/**
* 获取实体
* @param <T>
* @param entityClass 实体类
* @param entityId 实体id
* @return
*/
public T find(Serializable entityId);
/**
* 获取分页数据
* @param <T>
* @param entityClass 实体类
* @param firstindex 开始索引
* @param maxresult 需要获取的记录数
* @return
*/
public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql, Object[] queryParams,LinkedHashMap<String, String> orderby);
public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql, Object[] queryParams);
public QueryResult<T> getScrollData(int firstindex, int maxresult, LinkedHashMap<String, String> orderby);
public QueryResult<T> getScrollData(int firstindex, int maxresult);
public QueryResult<T> getScrollData();
}
package cn.yisi.service.base;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import cn.yisi.bean.QueryResult;
import cn.yisi.utils.GenericsUtils;
import cn.yisi.utils.WebUtil;
@SuppressWarnings("unchecked")
@Transactional
public abstract class DaoSupport<T> implements DAO<T> {
protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());
@PersistenceContext
protected EntityManager em;
public void clear() {
em.clear();
}
public void delete(Serializable... entityids) {
for (Object id : entityids) {
em.remove(em.getReference(this.entityClass, id));
}
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public T find(Serializable entityId) {
if (entityId == null)
throw new RuntimeException(this.entityClass.getName() + ":传入的实体id不能为空");
return em.find(this.entityClass, entityId);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public T getByID(String id, String colName) {
String realColName = "id";
if (!WebUtil.checkNull(colName)) {
realColName = colName;
}
if (id == null || "".equals(id.trim()))
throw new RuntimeException(this.entityClass.getName() + ":传入的实体id不能为空");
List<T> list = em.createQuery("select o from " + getEntityName(this.entityClass) + " o where " + realColName + " = ?1").setParameter(1, id).getResultList();
if (list != null && list.size() == 1) {
return list.get(0);
} else {
return null;
}
}
public void save(T entity) {
em.persist(entity);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public long getCount() {
return (Long) em.createQuery("select count(" + getCountField(this.entityClass) + ") from " + getEntityName(this.entityClass) + " o").getSingleResult();
}
public void update(T entity) {
em.merge(entity);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public QueryResult<T> getScrollData(int firstindex, int maxresult, LinkedHashMap<String, String> orderby) {
return getScrollData(firstindex, maxresult, null, null, orderby);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql, Object[] queryParams) {
return getScrollData(firstindex, maxresult, wherejpql, queryParams, null);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public QueryResult<T> getScrollData(int firstindex, int maxresult) {
return getScrollData(firstindex, maxresult, null, null, null);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public QueryResult<T> getScrollData() {
return getScrollData(-1, -1);
}
@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql, Object[] queryParams, LinkedHashMap<String, String> orderby) {
// 测试用--开始
// System.out.println("wherejpql--->"+wherejpql);
// for(int i=0;i<queryParams.length;i++){
// System.out.println("queryParams"+i+"--->"+queryParams[i]);
// }
// 测试用--结束
QueryResult qr = new QueryResult<T>();
String entityname = getEntityName(this.entityClass);
String tempSQLWhere = entityname + " o " + (wherejpql == null || "".equals(wherejpql.trim()) ? "" : "where " + wherejpql);
String tempSQL = "select o from " + tempSQLWhere + buildOrderby(orderby);
Query query = em.createQuery(tempSQL);
setQueryParams(query, queryParams);
if (firstindex != -1 && maxresult != -1) {
query.setFirstResult(firstindex).setMaxResults(maxresult);
}
qr.setResultlist(query.getResultList());
String tempCountSQL = "select count(" + getCountField(this.entityClass) + ") from " + tempSQLWhere;
query = em.createQuery(tempCountSQL);
setQueryParams(query, queryParams);
qr.setTotalrecord((Long) query.getSingleResult());
return qr;
}
protected static void setQueryParams(Query query, Object[] queryParams) {
if (queryParams != null && queryParams.length > 0) {
for (int i = 0; i < queryParams.length; i++) {
query.setParameter(i + 1, queryParams[i]);
}
}
}
/**
* 组装order by语句
*
* @param orderby
* @return
*/
protected static String buildOrderby(LinkedHashMap<String, String> orderby) {
StringBuffer orderbyql = new StringBuffer("");
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);
}
return orderbyql.toString();
}
/**
* 获取实体的名称
*
* @param <E>
* @param clazz
* 实体类
* @return
*/
protected static <E> String getEntityName(Class<E> clazz) {
String entityname = clazz.getSimpleName();
Entity entity = clazz.getAnnotation(Entity.class);
if (entity.name() != null && !"".equals(entity.name())) {
entityname = entity.name();
}
return entityname;
}
/**
* 获取统计属性,该方法是为了解决hibernate解析联合主键select count(o) from Xxx
* o语句BUG而增加,hibernate对此jpql解析后的sql为select
* count(field1,field2,...),显示使用count()统计多个字段是错误的
*
* @param <E>
* @param clazz
* @return
*/
protected 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;
}
}
分享到:
相关推荐
本示例主要介绍如何实现Spring Boot 2.0多数据源的集成,并结合Hibernate进行配置,特别是在DAO层使用`HibernateDaoSupport`进行操作,而非使用JPA(Java Persistence API)。 首先,让我们了解Spring Boot 2.0的...
7. **最佳实践**:在实际开发中,推荐使用Spring Data JPA,它是Spring对JPA规范的实现,可以进一步简化Hibernate的使用。通过Repository接口,开发者可以快速实现CRUD操作,而无需编写大量DAO代码。 总的来说,...
开发者可以通过 Spring 的 DaoSupport 类或 JPA 注解来编写数据访问层,这样可以轻松地集成事务管理。 在“SpringEnv”这个文件中,可能包含了配置 Spring MVC 和 Hibernate 4 所需的环境设置,例如 Spring 的配置...
- DaoSupport用于通用的DAO操作,封装分页功能,并使用自定义泛型。 - 文件上传下载通过IO和特定库如JSPSmartUpload、Spring的POI实现。 这份简历展示了应聘者扎实的Java Web开发基础,丰富的框架使用经验以及...