【问题标题】:Issue in hibernate criteria multiple tables data retrieval休眠条件多表数据检索中的问题
【发布时间】:2012-08-08 12:19:52
【问题描述】:

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

我的代码:

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")); 

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

提前致谢,
卡西。

【问题讨论】:

    标签: hibernate hibernate-mapping


    【解决方案1】:

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

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

    您可以尝试在集合映射上配置filter,或者只为每个项目执行新条件以检索过滤后的所需 itemvalue 集合。

    【讨论】:

    • if(itemvalue.getInputkey().equalsIgnoreCase("previewimage")) jobj.put("Location", itemvalue.getValue());在这里,我在检索时进行了过滤,并且收到了预期的输出,但是这是正确的做法吗?这是否会使流程变慢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多