Hibernate动态查询框架

来源:互联网 发布:软件调试报告模板 编辑:程序博客网 时间:2024/05/29 19:35
  1. 先定义一个枚举,配置条件查询是什么类型的,like = 还是between and。目前实现的是这三种  
  2.   
  3. -------------------------------------------------------------------------  
  4.   
  5. public enum CType {  
  6.     like,equal,between  
  7. }  
  8.   
  9.   
  10. -------------------------------------------------------------------------  
  11.   
  12. 定义annotation,用于注解在字段上面  
  13.   
  14.   
  15. import java.lang.annotation.ElementType;  
  16. import java.lang.annotation.Retention;  
  17. import java.lang.annotation.RetentionPolicy;  
  18. import java.lang.annotation.Target;  
  19.   
  20.   
  21. @Target(ElementType.FIELD)  
  22. @Retention(RetentionPolicy.RUNTIME)  
  23. public @interface ConditionType {  
  24.     CType value();  
  25.     String andField() default "";  
  26.     String queryField() default "";  
  27. }  
  28.   
  29. -------------------------------------------------------------------------  
  30.   
  31. 根据bean的字段注解生成查询语句  
  32.   
  33.   
  34. import java.lang.reflect.Field;  
  35. import java.lang.reflect.InvocationTargetException;  
  36. import java.lang.reflect.Method;  
  37. import java.util.List;  
  38.   
  39.   
  40. public class HqlCreator {  
  41.   
  42.      
  43.     public static void createHql(StringBuilder hql,Object object,List<Object> params)  
  44.     {  
  45.         try {  
  46.             //加载class  
  47.             Class clazz=object.getClass();  
  48.              
  49.             //获取私有字段  
  50.             Field[] fields=clazz.getDeclaredFields();  
  51.              
  52.             //遍历字段  
  53.             for (Field field : fields) {  
  54.                  
  55.                 //如果字段上有 ConditionType 的注解  
  56.                 if(field.isAnnotationPresent(ConditionType.class))  
  57.                 {  
  58.                     //获取注解的value值  
  59.                     ConditionType conditionType=field.getAnnotation(ConditionType.class);  
  60.                     CType ct=conditionType.value();  
  61.                      
  62.                     //调用get方法  
  63.                     Object objValue=invokeGetMethodByFieldName(field.getName(), object);  
  64.                      
  65.                      
  66.                     //获取字段类型  
  67.                     Class typeClass=field.getType();  
  68.                      
  69.                     if(objValue==null)  
  70.                         continue;  
  71.                      
  72.                     //检查字段是否为空  
  73.                     if(!checkTypeNull(typeClass,objValue)){  
  74.                         continue;  
  75.                     }  
  76.                      
  77.                     //根据注解类型生成相应的语句和参数  
  78.                     if(ct.equals(CType.equal))  
  79.                     {     
  80.                         hql.append(" and "+ field.getName() +" = ?");  
  81.                         params.add(objValue);  
  82.                     }  
  83.                     else if(ct.equals(CType.like))  
  84.                     {  
  85.                         hql.append(" and "+ field.getName() +" like ?");  
  86.                         params.add(Utils.returnLikeString(objValue.toString()));  
  87.                     }     
  88.                     else if(ct.equals(CType.between))  
  89.                     {  
  90.                         hql.append(" and " +conditionType.queryField()+ " between ? and ?");  
  91.                         params.add(objValue);  
  92.                         Object andValue=invokeGetMethodByFieldName(conditionType.andField(), object);  
  93.                         params.add(andValue);  
  94.                     }  
  95.                      
  96.                 }  
  97.                 System.out.println("生成hql语句为:"+hql.toString());  
  98.             }  
  99.         } catch (NumberFormatException e) {  
  100.             e.printStackTrace();  
  101.         } catch (SecurityException e) {  
  102.             e.printStackTrace();  
  103.         } catch (IllegalArgumentException e) {  
  104.             e.printStackTrace();  
  105.         }  
  106.     }  
  107.      
  108.      
  109.     //调用get方法  
  110.     public static Object invokeGetMethodByFieldName(String fieldName,Object object)  
  111.     {  
  112.         fieldName=fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);  
  113.         Method m=null;  
  114.         try {  
  115.             m = object.getClass().getMethod("get"+fieldName, null);  
  116.         } catch (SecurityException e) {  
  117.             // TODO Auto-generated catch block  
  118.             e.printStackTrace();  
  119.         } catch (NoSuchMethodException e) {  
  120.             // TODO Auto-generated catch block  
  121.             e.printStackTrace();  
  122.         }  
  123.         Object objValue=null;  
  124.         try {  
  125.             objValue = m.invoke(object, null);  
  126.         } catch (IllegalArgumentException e) {  
  127.             // TODO Auto-generated catch block  
  128.             e.printStackTrace();  
  129.         } catch (IllegalAccessException e) {  
  130.             // TODO Auto-generated catch block  
  131.             e.printStackTrace();  
  132.         } catch (InvocationTargetException e) {  
  133.             // TODO Auto-generated catch block  
  134.             e.printStackTrace();  
  135.         }  
  136.         return objValue;  
  137.     }  
  138.      
  139.      
  140.        private static boolean checkTypeNull(Class typeClass,Object objValue)  
  141.     {  
  142.         boolean flag=true;  
  143.          
  144.         if(typeClass.equals(String.class))  
  145.         {  
  146.             if(objValue==null || Utils.isEmpty(objValue+""))  
  147.                 flag=false;  
  148.         }  
  149.          
  150.         if(typeClass.equals(Long.class))  
  151.         {  
  152.             if(objValue==null || Long.parseLong(objValue.toString())==0L)  
  153.                 flag=false;  
  154.         }  
  155.          
  156.         //后续如果出现类型判断有误,在此添加  
  157.          
  158.         return flag;  
  159.     }  
  160.   
  161. }  
  162.   
  163.   
  164. -------------------------------------------------------------------------  
  165.   
  166. 这个是用户查询时必要的几个参数,封转成bean啦  
  167.   
  168.   
  169. import java.util.List;  
  170.   
  171. public class Paging {  
  172.     private String hql;  
  173.     private List<Object> params;  
  174.     private int start;  
  175.     private int limit;  
  176.      
  177.      
  178.     省略get、set     
  179. }  
  180.   
  181.   
  182.   
  183.   
  184. -------------------------------------------------------------------------  
  185.   
  186. 这个就是吧 paging 这个bean进行查询的  
  187.   
  188.   
  189. public class CommonsDAO extends HibernateDaoSupport{  
  190.     private static final Logger log = Logger.getLogger(CommonsDAO.class);  
  191.   
  192.     public List findByPageBean(final Paging page){  
  193.         if(page==null){  
  194.             return null;  
  195.         }  
  196.         List list = null;  
  197.         log.debug("分页查询");  
  198.         try {  
  199.             list = this.getHibernateTemplate().executeFind(  
  200.                     new HibernateCallback() {  
  201.   
  202.                         public Object doInHibernate(Session session)  
  203.                                 throws HibernateException, SQLException {  
  204.                             Query query = session.createQuery(page.getHql());  
  205.                             if(page.getParams()!=null)  
  206.                             {  
  207.                             for (int i = 0; i < page.getParams().size(); i++) {  
  208.                                 query.setParameter(i, page.getParams().get(i));  
  209.                             }  
  210.                             }  
  211.                             if(page.getLimit()!=0)  
  212.                             {  
  213.                             query.setFirstResult(page.getStart());  
  214.                             query.setMaxResults(page.getLimit());  
  215.                             }  
  216.                             List list = query.list();  
  217.                             return list;  
  218.                         }  
  219.                     });  
  220.             log.debug("分页查询成功");  
  221.         } catch (Exception e) {  
  222.             e.printStackTrace();  
  223.             log.error("分页查询失败",e);  
  224.             throw new RuntimeException("findByPageBean");  
  225.         }  
  226.         return list;  
  227.     }  
  228.   
  229.   
  230.   
  231.   
  232. public int findTotal(final Paging page) {  
  233.         int total=0;  
  234.         if(page==null)  
  235.         {  
  236.             return total;  
  237.         }  
  238.         log.debug("查询记录总数");  
  239.         try {  
  240.             total = Integer.parseInt((this.getHibernateTemplate().execute(  
  241.                     new HibernateCallback() {  
  242.                         public Object doInHibernate(Session session)  
  243.                                 throws HibernateException, SQLException {  
  244.                             Query query = session.createQuery(page.getHql());  
  245.                             if(page.getParams()!=null)  
  246.                             {  
  247.                             for (int i = 0; i < page.getParams().size(); i++) {  
  248.                                 query.setParameter(i, page.getParams().get(i));  
  249.                                  
  250.                             }  
  251.                             }  
  252.                             Object o=query.uniqueResult();  
  253.                             if(o!=null){  
  254.                                 return Integer.parseInt(o.toString());  
  255.                             }  
  256.                             return 0;  
  257.                         }  
  258.                     }).toString()));  
  259.             log.debug("查询记录总数成功");  
  260.         } catch (Exception e) {  
  261.             e.printStackTrace();  
  262.             log.error("查询记录总数失败",e);  
  263.             throw new RuntimeException("findTotal");  
  264.         }  
  265.         return total;  
  266.     }  
  267.   
  268. -------------------------------------------------------------------------  
  269.   
  270.   
  271. 现在我们写一个封装查询条件的bean  
  272.   
  273.   
  274. import java.util.Date;  
  275.   
  276. public class ZcjzclBean {  
  277.   
  278.   
  279.     /** 
  280.     * @Fields cphm : 车牌号码 
  281.     */  
  282.     @ConditionType(CType.like)  
  283.     private String cphm;  
  284.      
  285.     /** 
  286.     * @Fields jg : 价格 
  287.     */  
  288.     @ConditionType(value=CType.between,andField="jgEnd",queryField="jg")  
  289.     private Double jgStart;  
  290.     private Double jgEnd;  
  291.      
  292.     /** 
  293.     * @Fields lc : 里程 
  294.     */  
  295.     @ConditionType(value=CType.between,andField="lcEnd",queryField="lc")  
  296.     private Long lcStart;  
  297.     private Long lcEnd;  
  298.      
  299.     /** 
  300.     * @Fields lcdj : 里程单价 
  301.     */  
  302.     @ConditionType(value=CType.between,andField="lcdjEnd",queryField="lcdj")  
  303.     private Double lcdjStart;  
  304.     private Double lcdjEnd;  
  305.      
  306.     /** 
  307.     * @Fields bylc : 保养里程 
  308.     */  
  309.     @ConditionType(value=CType.between,andField="bylcEnd",queryField="bylc")  
  310.     private Long bylcStart;  
  311.     private Long bylcEnd;  
  312.      
  313.     /** 
  314.     * @Fields fzrid : 负责人id 
  315.     */  
  316.     @ConditionType(CType.equal)  
  317.     private Long fzrid;  
  318.      
  319.     /** 
  320.     * @Fields sjid : 司机id 
  321.     */  
  322.     @ConditionType(CType.equal)  
  323.     private Long sjid;  
  324.      
  325.     /** 
  326.     * @Fields gg : 规格 
  327.     */  
  328.     @ConditionType(CType.like)  
  329.     private String gg;  
  330.      
  331.     /** 
  332.     * @Fields xh : 型号 
  333.     */  
  334.     @ConditionType(CType.like)  
  335.     private String xh;  
  336.      
  337.     /** 
  338.     * @Fields zws : 座位数 
  339.     */  
  340.     @ConditionType(value=CType.between,andField="zwsEnd",queryField="zws")  
  341.     private Long zwsStart;  
  342.     private Long zwsEnd;  
  343.      
  344.     /** 
  345.     * @Fields ys : 颜色 
  346.     */  
  347.     @ConditionType(CType.equal)  
  348.     private String ys;  
  349.   
  350.     /** 
  351.     * @Fields gmrq : 购买日期 
  352.     */  
  353.     @ConditionType(value=CType.between,andField="gmrqEnd",queryField="gmrq")  
  354.     private Date gmrqStart;  
  355.     private Date gmrqEnd;  
  356.      
  357.     /** 
  358.     * @Fields jzrq : 建账日期 
  359.     */  
  360.     @ConditionType(value=CType.between,andField="jzrqEnd",queryField="jzrq")  
  361.     private Date jzrqStart;  
  362.     private Date jzrqEnd;  
  363.      
  364.     /** 
  365.     * @Fields zcjzrid : 资产建账人id 
  366.     */  
  367.     @ConditionType(CType.equal)  
  368.     private Long zcjzrid;  
  369.   
  370.   省略get、set  
  371. -------------------------------------------------------------------------  
  372.   
  373. 编写查询代码  
  374.   
  375.   
  376.   
  377. import java.util.ArrayList;  
  378. import java.util.List;  
  379.   
  380. import org.apache.log4j.Logger;  
  381.   
  382.   
  383. public class ZcjzclServiceImpl implements ZcjzclService {  
  384.     public static final Logger log=Logger.getLogger(ZcjzclServiceImpl.class);  
  385.     private CommonsDAO commonsDAO;  
  386.      
  387.     public List<TZcjzcl> queryByCondition(ZcjzclBean bean,int start,int limit)  
  388.     {  
  389.         try {  
  390.             log.debug(" ");  
  391.             Paging page=getPage( bean, start, limit, false);  
  392.             List<TZcjzcl> cls=commonsDAO.findByPageBean(page);  
  393.             return cls;  
  394.         } catch (RuntimeException e) {  
  395.             log.error(" 异常");  
  396.             throw e;  
  397.         }  
  398.          
  399.     }  
  400.      
  401.      
  402.     public int queryTotalByCondition(ZcjzclBean bean, int start, int limit) {  
  403.         try {  
  404.              
  405.             log.debug(" ");  
  406.             Paging page=getPage( bean, start, limit, true);  
  407.             int total=commonsDAO.findTotal(page);  
  408.             return total;  
  409.         } catch (RuntimeException e) {  
  410.             log.error(" 异常",e);  
  411.             throw e;  
  412.         }  
  413.     }  
  414.      
  415.      
  416.     private Paging getPage(ZcjzclBean bean, int start, int limit,boolean isTotal)  
  417.     {  
  418.         try {  
  419.             log.debug("组装查询语句及条件");  
  420.             List<Object> params=new ArrayList<Object>();  
  421.             StringBuilder hql=new StringBuilder();  
  422.             if(isTotal)  
  423.                 hql.append("select count(*) from TZcjzcl where 1=1 ");  
  424.             else  
  425.                 hql.append("from TZcjzcl where 1=1 ");  
  426.              
  427.             if(bean!=null)  
  428.             {  
  429.                 HqlCreator.createHql(hql, bean, params);  
  430.             }  
  431.              
  432.             Paging page=new Paging();  
  433.             page.setHql(hql.toString());  
  434.             page.setStart(start);  
  435.             page.setLimit(limit);  
  436.             page.setParams(params);  
  437.              
  438.             return page;  
  439.         } catch (RuntimeException e) {  
  440.             log.error("组装查询语句及条件异常",e);  
  441.             throw e;  
  442.         }  
  443.     }  
  444.      
  445.     
  446.      省略get、set  
  447. }  
  448.   
  449.   
  450.   
  451.   
  452. -------------------------------------------------------------------------  
  453.   
  454. 要加什么条件直接在查询条件bean里面加就完啦。
  455. 原文链接:http://busing.iteye.com/blog/850086
0 0
原创粉丝点击