在java中使用@Filter hibernate注释过滤集合 [英] Filtering a collection using the @Filter hibernate annotation in java
问题描述
有2个实体B集合,我想根据B中的属性过滤每个集合(如下面的代码所示)。
@FilterDefs()
class A {
@OneToMany(mappedBy =productType,fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@Filter(name =something,condition =entityType ='SKU1')
Set< ; B个set1 = new HashSet< B>();
@OneToMany(mappedBy =productType,fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@Filter(name =something,condition =entityType ='SKU2' )
设置< B> set2 = new HashSet< B>();
class B {
@ManyToOne(cascade = CascadeType.ALL)
private productType;
@Column(name =entity_type)
@Enumerated(EnumType.STRING)
private EntityType entityType;
}
编辑:
我按照以下建议启用过滤器DAO方法。但是,我收到以下异常:
$ b
org.hibernate.exception.SQLGrammarException:无法初始化
>
集合
如果我使用急切的加载方法,我得到一个异常来处理生成的无效SQL?
任何指针?
我在实体中使用FilterDef,然后设置我想要使用的极其集合过滤器。在你的例子中:
class A {
@OneToMany(...)
@Filter(name =filterName)
设置< B> set2 = new HashSet< B>();
$ b $ @FilterDef(name =filterName,
defaultCondition = condition,
parameters = {@ParamDef(name = nameParameter,
type =然后,正如ssedano所说的那样,你可以通过使用它来创建一个新的数据库,应在会话中启用过滤器: session.enableFilter(filterName)
如果是这种情况,请输入参数:
session.getEnabledFilter(FILTERNAME).setParameter(nameParameter,值);
I have two hibernate mapped entities A and B.
A has 2 collections of entity B and I would like to filter each collection based on a property held in B (as shown in code below).
@FilterDefs()
class A{
@OneToMany(mappedBy = "productType", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Filter(name = "something", condition = "entityType = 'SKU1'")
Set<B> set1 = new HashSet<B>();
@OneToMany(mappedBy = "productType", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@Filter(name = "something", condition = "entityType = 'SKU2'")
Set<B> set2 = new HashSet<B>();
}
class B{
@ManyToOne(cascade = CascadeType.ALL)
private A productType;
@Column(name = "entity_type")
@Enumerated(EnumType.STRING)
private EntityType entityType;
}
Edited:
I am enabling the filters as suggested below in my DAO method. However, I am getting the following exception
org.hibernate.exception.SQLGrammarException: could not initialize a
collection
If i use the eager loading method, I am getting an exception to do with invalid SQL getting generated?
Any pointers?
解决方案 I use FilterDef in the Entity and then set in wich collections I want to use the filter. In your example:
class A{
@OneToMany(...)
@Filter(name = "filterName")
Set<B> set2 = new HashSet<B>();
}
@FilterDef(name = "filterName",
defaultCondition = condition,
parameters = {@ParamDef(name = nameParameter,
type = typeParameter)})
class B{
}
Then as ssedano said you should enable filter in the session:
session.enableFilter("filterName")
And put the params if it is the case:
session.getEnabledFilter(filterName).setParameter(nameParameter,value);
这篇关于在java中使用@Filter hibernate注释过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!