问题描述
findByCriteria(...)应该怎么用?public List<T> findByCriteria(Criterion... criterion) { return createCriteria(criterion).list(); }这个方法应该怎么用?比如表结构如下id pkmoney floattype_id fk按照type_id分组求sum(money) 在dao里应该怎么写?
解决方案
首先这是Hibernate的QBC检索方式,建议baidu下QBC,或者看书和API。下面是我写过的一个项目中的代码片段,这是DAO的片段public List<DispatchTask> findByCriteria(DetachedCriteria criteria) { log.debug("finding DispatchTask instance by criteria"); try { List<DispatchTask> results = getHibernateTemplate().findByCriteria(criteria); log.debug("find by criteria successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by criteria failed", re); throw re; } }这是Service的片段public List<DispatchTask> getByQuery(DispatchTask instance,Date queryTime1, Date queryTime2) {String taskId = instance.getTaskId();String deptName = instance.getDeptName();String linkman = instance.getLinkman();String plateNum = instance.getPlateNum();Short statusId = instance.getStatusId();Date queryTime3 = null;if(queryTime2 != null){queryTime3 = new Date();queryTime3.setTime(queryTime2.getTime()+(new Long("86400000")));}DetachedCriteria criteria = DetachedCriteria.forClass(DispatchTask.class);if (taskId != null && taskId != "") {criteria.add(Expression.like("taskId", taskId, MatchMode.ANYWHERE));}if (deptName != null && deptName != "") {criteria.add(Expression.like("deptName", deptName,MatchMode.ANYWHERE));}if (linkman != null && linkman != "") {criteria.add(Expression.like("linkman", linkman, MatchMode.ANYWHERE));}if (plateNum != null && plateNum != "") {criteria.add(Expression.like("plateNum", plateNum,MatchMode.ANYWHERE));}if (statusId != null && statusId != 999) {criteria.add(Expression.eq("statusId", statusId));}if (queryTime1 != null) {if(queryTime2 != null){if(queryTime1.getTime() <= queryTime2.getTime()){criteria.add(Expression.between("dispatchDate", queryTime1,queryTime3));}}else{criteria.add(Expression.ge("dispatchDate", queryTime1));}}else{if(queryTime2 != null){criteria.add(Expression.le("dispatchDate", queryTime3));}}return dispatchTaskDAO.findByCriteria(criteria);}关键是给出规则,即Criterion,DetachedCriteria是继承它的。这个找个Hibernate的API就了解了。至于您说的例子,DAO就是DatabaseAccessObject,我觉得您把逻辑放进DAO里是不是违反了面向对象的思想呢?我不喜欢这么设计
解决方案二:
看了一下,发现这个Service里的方法写的是够烂的,我来解释一下。这个方式其实是一个多条件查询,用户不填写的话,代表忽略此条件。所以做了N次if判断