2

在这里,我遇到了休眠条件使用的问题,我为多个表创建了条件并添加了限制,但输出与预期不符

我的代码:

final Criteria crit = session2.createCriteria(Item.class, "item");   
            crit.createCriteria("itemvalues", "values");   
            crit.createCriteria("categoryitemses", "catItems");   
            crit.createCriteria("catItems.category", "cat");   
            crit.createCriteria("cat.categorytype", "catType");    
            crit.createCriteria("cat.categoryproducts", "catProd");    
            crit.createCriteria("catProd.product", "prod");    
            crit.createCriteria("prod.customer", "cust");   
            crit.add(Restrictions.eq("catType.id", id));   
            crit.add(Restrictions.eq("cust.id", custId));   
            crit.add(Restrictions.eq("values.inputkey", "previewimage"));   
            crit.addOrder(Order.asc("item.id"));

在 Item.java 我有以下属性

private Itemtype itemtype;   
private String name;   
private String description;   
private Set<Itemvalue> itemvalues = new HashSet<Itemvalue>(0);   
private Set<Categoryitems> categoryitemses = new HashSet<Categoryitems>(0); 

ItemValue 表包含一个字段名称 inputkey,其中包含 previewimage 和 content 等条目,但我只需要检索 previewimage 输入键。

但是在输出中 inputkeys 也带有一些其他值。

我发现 hibernate 生成的查询运行正确并按预期提供输出,但是在查询之后,当我使用 set 检索 itemvalue 时,还会执行其他几个查询

final Set<Itemvalue> itemValues = itemList.get(innerIndex).getItemvalues();   
final Iterator<Itemvalue> itemVals = itemValues.iterator();    
while(itemVals.hasNext()) {   
jobj.put("Location", itemVals.next().getValue());    
}

这里在行 itemValues.iterator hibernate 查询中执行了 17 次,因为总输出是 17 个项目,每个项目都获取 itemvalue 但忽略了前面给出的条件

crit.add(Restrictions.eq("values.inputkey", "previewimage")); 

我在这里缺少什么?任何人都请帮我解决这个问题!

在此先感谢,
卡尔蒂。

4

1 回答 1

1

您的原始查询使用Restrictions.eq("values.inputkey", "previewimage")限制来过滤掉Item对象而不是Itemvalue对象。

何时getItemvalues()调用 Hibernate 集合映射用于检索对象而不是原始查询。如果集合映射没有什么特别之处,则将返回未过滤的相关项值对象集合。

You could try to configure a filter on the collection mapping or just execute a new criteria for each item to retrieve the filtered desired itemvalue collection.

于 2012-08-08T12:49:30.070 回答