Gerardo Martínez
Gerardo Martínez

Reputation: 863

How can I filter data based on a property value?

Let's say I have the table Survey and the Table Attachment related to it. Whenever I get the Survey data I use:

Survey survey = iSurveyRepository.findOne(id); 

That is going to get the Survey data and all the Attachments related to it as a list of objects and that's fine, but what I want is to get the Survey data but only the Attachments uploaded by me. (The Attachment entity has an added_by field).

I have heard hibernate has something called filters but I'm not sure how to implement them using annotation based configuration.

Upvotes: 1

Views: 34

Answers (1)

Aeseir
Aeseir

Reputation: 8434

What you are after essentially is Criteria Queries within Hibernate:

Hibernate Criteria Queries

Essentially what it means you make queries with Criterion (criteria in plain english) and it calls relevant queries.

e.g.

String user = "John";

List surveys = sess.createCriteria(Survey.class)
    .add( Restrictions.like("id", id) )
    .add( Restrictions.like("attachment.added_by", user) )  //where user is a string variable
    .list();

This will return all surveys that have attachments created by any user containing text "John".

Upvotes: 2

Related Questions