Search code examples
hibernatehibernate-annotations

How do I get Hibernate Filters to work in JPA?


I have the following entity class:


@Entity
@FilterDef (name = "byLastName", parameters = @Parameter (name = "lastName", type="string"))
@Filters ({
    @Filter (name = "byLastName", condition = "lastName = :lastName")
})
public class User {
    String firstName;
    String lastName;
}

In my DAO I do this:


public User findById (Long id)
{
   Session s = (Session) em.getDelegate ( );
   s.enableFilter ("byLastName").setParameter ("lastName", "smith");

   User u = em.find (User.class, id);
   return (u);
}

Now, if I'm understanding this correctly, the filter should be applied, and any User that I try to retrieve should come back as null if the lastName does not equal "smith". The problem is that the filters don't appear to be applied. Any User that I attempt to retrieve from the database, regardless of the value of the lastName gets returned.

Am I misunderstanding how filters work? Or am I missing something in how I have this configured? Note that I'm not using hibernate.cfg.xml; everything is configured for me using JPA and annotations.

Any help would be greatly appreciated.

Thanks.


Solution

  • Filters do not affect any form of look up by ids. This is also the exact reason one-to-one and many-to-one associations cannot be filtered.