我有一个看起来像这样的数据模型:
public class Item {
private List<ItemAttribute> attributes;
// other stuff
}
public class ItemAttribute {
private String name;
private String value;
}
(这显然简化了很多无关的东西)
我想要做的是创建一个查询来询问具有一个或多个特定属性的所有项目,最好用任意 AND 和 OR 连接。现在我保持简单,只是尝试实现 AND 案例。在伪 SQL(或者伪 HQL,如果你愿意的话)中,它会是这样的:
select all items
where attributes contains(ItemAttribute(name="foo1", value="bar1"))
AND attributes contains(ItemAttribute(name="foo2", value="bar2"))
Hibernate 文档中的示例似乎没有解决这一特定用例,但它似乎是一个相当常见的用例。析取情况也很有用,特别是这样我可以指定可能值的列表,即
where attributes contains(ItemAttribute(name="foo", value="bar1"))
OR attributes contains(ItemAttribute(name="foo", value="bar2"))
-- etc.
下面是一个适用于单个属性的示例:
return getSession().createCriteria(Item.class)
.createAlias("itemAttributes", "ia")
.add(Restrictions.conjunction()
.add(Restrictions.eq("ia.name", "foo"))
.add(Restrictions.eq("ia.attributeValue", "bar")))
.list();
学习如何做到这一点对于扩展我对 Hibernate 潜力的理解大有帮助。 :)