我有一个看起来像这样的数据模型:
public class Item {
private List<ItemAttribute> attributes;
// other stuff
}
public class ItemAttribute {
private String name;
private String value;
}
Run Code Online (Sandbox Code Playgroud)
(这显然简化了很多无关紧要的东西)
我想要做的是创建一个查询来询问具有一个或多个特定属性的所有项目,理想情况下使用任意AND和OR连接.现在我保持简单,只是试图实现AND案例.在伪SQL(或伪HQL,如果你愿意),它将是这样的:
select all items
where attributes contains(ItemAttribute(name="foo1", value="bar1"))
AND attributes contains(ItemAttribute(name="foo2", value="bar2"))
Run Code Online (Sandbox Code Playgroud)
Hibernate文档中的示例似乎没有解决这个特定的用例,但它似乎是一个相当普遍的用例.分离案例也很有用,特别是我可以指定一个可能的值列表,即
where attributes contains(ItemAttribute(name="foo", value="bar1"))
OR attributes contains(ItemAttribute(name="foo", value="bar2"))
-- etc.
Run Code Online (Sandbox Code Playgroud)
这是一个适用于单个属性的示例:
return getSession().createCriteria(Item.class)
.createAlias("itemAttributes", "ia")
.add(Restrictions.conjunction()
.add(Restrictions.eq("ia.name", "foo"))
.add(Restrictions.eq("ia.attributeValue", "bar")))
.list();
Run Code Online (Sandbox Code Playgroud)
学习如何做到这一点将大大有助于扩展我对Hibernate潜力的理解.:)
SELECT item FROM Item item JOIN item.attributes attr
WHERE attr IN (:attrList) GROUP BY item
Run Code Online (Sandbox Code Playgroud)
然后在Java代码中:
List<ItemAttribute> attrList = new ArrayList<ItemAttribute>();
attrList.add(..); // add as many attributes as needed
...// create a Query with the above string
query.setParameter("attrList", attrList);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11179 次 |
| 最近记录: |