如何在休眠中对两个加入的实体应用限制

How to apply restriction on both joined entities in hibernate

class Category{

    @Id
    @Column(name="ID")
    private Integer id;
    private String name;

    @OneToMany
    @JoinColumn(name="CATEGORY_ID",referencedColumnName="ID")
    private Set<Item> items;

}

class Item{

    private Integer id;

    @Column(name="CATEGORY_ID")
    private Integer categoryId;

    private String name;

    private String color;
}

这里我有两个具有一对多关系的实体(类别和项目)。

我试图获取类别 ID =5 且项目颜色 =red 下的项目。 我希望结果类似于

{ id:5, name:'fruits' items:[{id:3,name:"tomato",color:red},{id:55,name:"apple", color:"red"}] }

Criteria c=session.createCriteria("Category.class","cat");
c.createAlias("cat.items","it");
c.add(Restrictions.eq("cat.id,5));
c.add(Restrictions.eq("it.color","red"));

List<Category> cateList=c.list();

但是我得到了类别 id =5 中的所有项目; 浪费了很多time.NeedHelp.Thanks

Category            
ID  NAME        
1   Flower      
5   Fruit       


Item            
ID  CATEGORY_ID NAME    COLOR
3   5           tomato  red
55  5           apple   red
4   5           banana  yellow
6   5           orange  orange
7   5           grape   green
1   1           rose    red
2   1           rose    yellow

我会看一下 Hibernate @Filter@FilterDef 注释。

您基本上想要做的是定义一个过滤器,在获取集合中的条目时将颜色谓词应用于集合中的条目,以便只有适用的条目才会出现在集合中。

@Entity
public class Category {
  @OneToMany
  @Filter(name = "itemsByColor")
  private Set<Item> items;
}

@Entity
@FilterDef(name = "itemsByColor",
  defaultCondition = "color = :color",
  parameters = { @ParamDef(name = "color", type = String.class ) })
public class Item {
  private String color;
}

您需要做的是在执行查询之前启用该过滤器:

session.enableFilter( "itemsByColor" )
       .setParameter( "color", "red" );

现在执行您的查询:

Criteria c=session.createCriteria("Category.class","cat");
c.createAlias("cat.items","it");
c.add(Restrictions.eq("cat.id,5));
c.add(Restrictions.eq("it.color","red"));
List<Category> cateList=c.list();

您返回的 Category 个实例现在应该只包含颜色为 redItem 个实例。

请注意,启用过滤器后,它会在整个会话期间保持有效。

有时专门为这样的一个查询启用过滤器并在检索到结果后立即将其禁用以避免针对 Category.

的其他查询的错误结果。