Reza Ghafari

Hibernate Filters

This is one way of writing a Hibernate filter. We have to define a filter first using @FilterDef as a global annotation, meaning that it can be applied anywhere in the code.

Then we apply the filter to where ever we want using @Filter and then we need to enable the filter in the session.

The reason for the filter is that when I do A.getstateTransitions() I want the list of B’s returned to be filtered.

@FilterDef(name=“myfilter”, defaultCondition=“TRANSITION_DATE > trunc (sysdate)”)

class A{

@OneToMany(…) @Filter(name=“myfilter”) private List stateTransitions;

}

class B{

@NotNull @Column (name=“TRANSITION_DATE”, columnDefinition=“DATE”) private Calendar transitionDate;

}

Using:

org.hibernate.Session session = (Session) entityManager.getDelegate(); session.enableFilter(“myfilter”); query.getResultList() // returns list of A’s where B.stateTransitions are after now.

Filters can have parameters but I didn’t need one here.