首先这是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里是不是违反了面向对象的思想呢?我不喜欢这么设计