我有一个看起来像这样的数据模型:
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 潜力的理解。 :)
最佳答案
你能使用别名来做到这一点吗?
Criteria itemCriteria = session.createCriteria(Item.class);
itemCriteria.createAlias("itemAttributes", "ia1")
.createAlias("itemAttributes", "ia2")
.add(Restrictions.eq("ia1.name", "foo1"))
.add(Restrictions.eq("ia1.attributeValue", "bar1")))
.add(Restrictions.eq("ia2.name", "foo2"))
.add(Restrictions.eq("ia2.attributeValue", "bar2")))
不确定 hibernate 如何像那样显式处理加入同一属性两次,也许值得一试?
关于java - Hibernate 查询集合中的多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3001136/