JavaWeb项目开发案例精粹-第6章报价管理系统-03Dao层

1.

 1 package com.sanqing.dao;
 2 
 3 import java.io.Serializable;
 4 import java.util.LinkedHashMap;
 5 
 6 import com.sanqing.util.QueryResult;
 7 
 8 
 9 public interface DAO<T> {
10     public long getCount();//获得记录总数
11     public void clear();//清除一级缓存的数据
12     public void save(Object entity);//保存记录
13     public void update(Object entity);//更新记录
14     public void delete(Serializable ... entityids);//删除记录
15     public T find(Serializable entityId);//通过主键获得记录
16     public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql, 
17                     Object[] queryParams,LinkedHashMap<String, String> orderby);//获得分页记录
18     public QueryResult<T> getScrollData(int firstindex, int maxresult,
19                                         String wherejpql, Object[] queryParams);//获得分页记录
20     public QueryResult<T> getScrollData(int firstindex, int maxresult,
21                                         LinkedHashMap<String, String> orderby);//获得分页记录
22     public QueryResult<T> getScrollData(int firstindex, int maxresult);        //获得分页记录
23     public QueryResult<T> getScrollData();//获得分页记录
24 }

2.

  1 package com.sanqing.dao;
  2 
  3 import java.beans.Introspector;
  4 import java.beans.PropertyDescriptor;
  5 import java.io.Serializable;
  6 import java.lang.reflect.Method;
  7 import java.util.LinkedHashMap;
  8 
  9 import javax.persistence.EmbeddedId;
 10 import javax.persistence.Entity;
 11 import javax.persistence.EntityManager;
 12 import javax.persistence.PersistenceContext;
 13 import javax.persistence.Query;
 14 
 15 import org.springframework.transaction.annotation.Propagation;
 16 import org.springframework.transaction.annotation.Transactional;
 17 
 18 import com.sanqing.util.GenericsUtils;
 19 import com.sanqing.util.QueryResult;
 20 
 21 @SuppressWarnings("unchecked")
 22 @Transactional
 23 public abstract class DaoSupport<T> implements DAO<T>{
 24     protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());//获得该类的父类的泛型参数的实际类型
 25     @PersistenceContext protected EntityManager em;
 26     public void clear(){//清除一级缓存的数据
 27         em.clear();
 28     }
 29     public void delete(Serializable ... entityids) {//删除记录
 30         for(Object id : entityids){
 31             em.remove(em.getReference(this.entityClass, id));
 32         }
 33     }
 34     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
 35     public T find(Serializable entityId) {//通过主键获得记录
 36         if(entityId==null) throw new RuntimeException(this.entityClass.getName()+ ":传入的实体id不能为空");
 37         return em.find(this.entityClass, entityId);
 38     }
 39     public void save(Object entity) {//保存记录
 40         em.persist(entity);
 41     }
 42     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
 43     public long getCount() {    //获得记录总数
 44         return (Long)em.createQuery("select count("+ getCountField(this.entityClass) +") from "+ getEntityName(this.entityClass)+ " o").getSingleResult();
 45     }
 46     
 47     protected static <E> String getCountField(Class<E> clazz){
 48         String out = "o";
 49         try {
 50             PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
 51             for(PropertyDescriptor propertydesc : propertyDescriptors){
 52                 Method method = propertydesc.getReadMethod();
 53                 if(method!=null && method.isAnnotationPresent(EmbeddedId.class)){                    
 54                     PropertyDescriptor[] ps = Introspector.getBeanInfo(propertydesc.getPropertyType()).getPropertyDescriptors();
 55                     out = "o."+ propertydesc.getName()+ "." + (!ps[1].getName().equals("class")? ps[1].getName(): ps[0].getName());
 56                     break;
 57                 }
 58             }
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         }
 62         return out;
 63     }
 64     
 65     protected static void setQueryParams(Query query, Object[] queryParams){
 66         if(queryParams!=null && queryParams.length>0){
 67             for(int i=0; i<queryParams.length; i++){
 68                 query.setParameter(i+1, queryParams[i]);
 69             }
 70         }
 71     }
 72     protected static String buildOrderby(LinkedHashMap<String, String> orderby){//组装order by语句
 73         StringBuffer orderbyql = new StringBuffer("");
 74         if(orderby!=null && orderby.size()>0){
 75             orderbyql.append(" order by ");
 76             for(String key : orderby.keySet()){
 77                 orderbyql.append("o.").append(key).append(" ").append(orderby.get(key)).append(",");
 78             }
 79             orderbyql.deleteCharAt(orderbyql.length()-1);
 80         }
 81         return orderbyql.toString();
 82     }
 83     protected static <E> String getEntityName(Class<E> clazz){//获取实体的名称
 84         String entityname = clazz.getSimpleName();
 85         Entity entity = clazz.getAnnotation(Entity.class);
 86         if(entity.name()!=null && !"".equals(entity.name())){
 87             entityname = entity.name();
 88         }
 89         return entityname;
 90     }
 91     
 92     public void update(Object entity) {//更新记录
 93         em.merge(entity);
 94     }
 95     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
 96     public QueryResult<T> getScrollData(int firstindex, 
 97                 int maxresult, LinkedHashMap<String, String> orderby) {//获得分页记录
 98         return getScrollData(firstindex,maxresult,null,null,orderby);
 99     }
100     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
101     public QueryResult<T> getScrollData(int firstindex, 
102             int maxresult, String wherejpql, Object[] queryParams) {//获得分页记录
103         return getScrollData(firstindex,maxresult,wherejpql,queryParams,null);
104     }
105     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
106     public QueryResult<T> getScrollData(int firstindex, int maxresult) {//获得分页记录
107         return getScrollData(firstindex,maxresult,null,null,null);
108     }
109     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
110     public QueryResult<T> getScrollData() {
111         return getScrollData(-1, -1);
112     }
113     @Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
114     public QueryResult<T> getScrollData(int firstindex, int maxresult, String wherejpql,
115             Object[] queryParams,LinkedHashMap<String, String> orderby) {//获得分页记录
116         QueryResult qr = new QueryResult<T>();//查询记录结果
117         String entityname = getEntityName(this.entityClass);//获得实体名称
118         Query query = em.createQuery("select o from "+ 
119                 entityname+ " o "+(wherejpql==null 
120                 || "".equals(wherejpql.trim())? "":
121                 "where "+ wherejpql)+ buildOrderby(orderby));//执行查询
122         setQueryParams(query, queryParams);//设置查询参数
123         if(firstindex!=-1 && maxresult!=-1) //两个参数都不是-1的时候才分页
124             query.setFirstResult(firstindex).
125             setMaxResults(maxresult);//设置查询记录的起始位置和查询最大数
126         qr.setResultlist(query.getResultList());//设置查询的记录
127         query = em.createQuery("select count(" +
128                 getCountField(this.entityClass)+ ") " +
129                 "from "+ entityname+ " o "+(wherejpql==null ||
130                 "".equals(wherejpql.trim())? "": "where "+ wherejpql));
131         setQueryParams(query, queryParams);//设置查询参数
132         qr.setTotalrecord((Long)query.getSingleResult());//设置查询记录总数
133         return qr;//返回查询记录结果
134     }
135 
136     
137 }

 

原文地址:https://www.cnblogs.com/shamgod/p/5328279.html