Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering a collection using the @Filter hibernate annotation in java

Tags:

hibernate

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?

like image 542
Mahesh Avatar asked Oct 18 '11 10:10

Mahesh


1 Answers

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);
like image 84
adrian.riobo Avatar answered Oct 23 '22 04:10

adrian.riobo