Hibernate中离线查询DetachedCriteria案例
2017-04-13 12:43
357 查看
Hibernate中离线查询经常用到。
问题:但当查询条件并不仅仅涉及到一个实体,而是还含有关联的实体中的属性时,就不知道怎么弄了。自己摸索了好久才发现原来API中已经提供了相应的解决方法。
情况1:
涉及到一个实体
查询条件涉及到的是Goods,如果查询时查询的是Goods表,那简单了
Service层
情况2:
但实际情况是:这是查询出入库操作历史的查询页面,所以Action中使用模型驱动时的
Model是History而非Store了,尽管这些参数最终还是封装到了History关联的Goods中。自然的传到Service层时的参数就不是上面代码中的Goods了,而是History了。这是就要用到”取别名“方式了。
问题:但当查询条件并不仅仅涉及到一个实体,而是还含有关联的实体中的属性时,就不知道怎么弄了。自己摸索了好久才发现原来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); }
相关文章推荐
- Hibernate中离线查询DetachedCriteria案例
- Hibernate离线查询(DetachedCriteria)
- hibernate离线查询DetachedCriteria清除上次的查询条件
- Hibernate-DetachedCriteria离线查询
- DetachedCriteria离线查询 org.hibernate.criterion.DetachedCriteria; org.hibernate.criterion.Restrictions;
- DetachedCriteria离线查询离线查询---实现模糊查询 Hibernate
- 应用Hibernate3的DetachedCriteria实现分页查询
- 灵活使用Hibernate的查询对象DetachedCriteria
- 离线查询和子查询--DetachedCriteria
- 灵活使用Hibernate的查询对象DetachedCriteria
- DetachedCriteria离线查询示例
- (hibernate查询)DetachedCriteria对象创建可以不需要使用session去创建
- 19 Criteria查询,DetachedCriteria离线查询 --做综合查询
- 应用Hibernate3的DetachedCriteria实现分页查询
- 应用Hibernate3的DetachedCriteria实现分页查询
- Criteria查询,DetachedCriteria离线查询 --做综合查询
- Hibernate使用DetachedCriteria和Criteria查询
- Hibernate之DetachedCriteria动态条件查询
- Hibernate3的DetachedCriteria实现分页查询
- 关于Hibernate的DetachedCriteria查询的addOrder问题的解决办法