I want to use the hibernate filter but I don't know if what I want to do is possible
I have 2 entities :
Message and MessageUser.
A Message has a list of MessageUser.
I want to create a filter so I can do something like :
final Session filteredSession = sessionFactory.openSession();
final Filter filter = filteredSession.enableFilter("userRecipient");
filter.setParameter("userRecipient", myUser);
filter.validate();
final List<Message> userMessages = filteredSession.createQuery("from Message").list();
it returns me only the message where myUser is the recipient ?
is it possible to to and how?
Thanks a lot !
If you are comfortable with Criteria you could create criteria like this
Have a look at this for reference while creating criteria!
If you only want to use filter then I hope you have configured filter on your
User
List
some thing like bellowBy *.hbm.xml
Or By annotation
after this you will be able get your filter working
Update
Purpose of
Filter
is different than theCriteria
, from my understanding you can say thatFilter
is just like a Criteria that is already applied on your class or collection which hason
andoff
switch. If your hibernate session has certain filter enabled with it's parameters set than that filter ison
and all queries relating to the class or collection which has this filter specified will always return filtered result as per the condition. This means you don't have to explicitly define it every time and by usinggetEnabledFilter("filterName")
you can just change that filter's parameters any time.Example usage of filter can be if you have
Movies
table andActor
table with many-to-many relationship, likeLeonardo Dicaprio
can have many movies at the same times Atitanic
can have many actors, here when you getActor
obviously you would want only those movies which thisActor
has performed in, so you can use filter here which is applied on collection ofMovies
that is mapped inActor
class. This way when you getActor
object say by simple criteria of name and nothing else and access it'sMovie
collection by.
operator onActor
object it will return you only movies which that actor has performed. This also means no matter how you gotActor
object from database when you accessMovie
collection ofActor
it will provide you movies that this actor has performed inCriteria on the other hand you can use when you require result from database with certain conditions which does not need to be replicated rather you don't want it to be replicated later in the hibernate session. Like
Actor
lets sayLeonardo Dicaprio
containing collection ofMovies
that got nominated him in Oscar. This collection will only be populated inActor
object when gone through certain criteria and will not be available on otherActor
objects which have not being retrieved by this criteria.I hope you understood basic concept of filter and criteria, and from my understanding of your problem it will be better if you use criteria!