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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With