您的位置:首页 > 其它

Hibernate中离线查询DetachedCriteria案例

2017-04-13 12:43 357 查看
Hibernate中离线查询经常用到。

问题:但当查询条件并不仅仅涉及到一个实体,而是还含有关联的实体中的属性时,就不知道怎么弄了。自己摸索了好久才发现原来API中已经提供了相应的解决方法。

情况1:

涉及到一个实体



查询条件涉及到的是Goods,如果查询时查询的是Goods表,那简单了

Service层

public List<History> findByCondition(Goods goods) {
DetachedCriteria dc=DetachedCriteria.forClass(History.class);
if(goods().getNm()!=null){
dc.add(Restrictions.like("nm", "%"+goods().getNm()+"%"));
}
……
return goodsDao.findByDetached(dc);
}


情况2:

但实际情况是:这是查询出入库操作历史的查询页面,所以Action中使用模型驱动时的
Model是History而非Store了,尽管这些参数最终还是封装到了History关联的Goods中。自然的传到Service层时的参数就不是上面代码中的Goods了,而是History了。这是就要用到”取别名“方式了。

public List<History> findByCondition(History history) {
DetachedCriteria dc=DetachedCriteria.forClass(History.class,"h");//别名:History对应h
dc.createAlias("h.goods", "g");//别名:Goods对应g
dc.createAlias("h.goods.store","s");//别名:Store对应s
if(history.getGoods().getNm()!=null){
dc.add(Restrictions.like("g.nm", "%"+history.getGoods().getNm()+"%"));
}
if(history.getGoods().getName()!=null){
dc.add(Restrictions.like("g.name", "%"+history.getGoods().getName()+"%"));
}
if(history.getGoods().getStore()!=null){
dc.add(Restrictions.like("s.id", "%"+history.getGoods().getStore().getId()+"%"));
}
return historyDao.findByDetached(dc);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: