sasha123
sasha123

Reputation: 21

Hibernate criteria filter inner collection

I have the next classes/tables:

User

Work

And the following code:

Criteria criteria = session.createCriteria("User"); 
criteria.list();

returns a list of Users that contain list of Work object assotiated with them (by id=user_id).

How can I modify this query to get the same list of User but with the follow restriction: List of Work should not includes Works where name ='fck'?

Upvotes: 2

Views: 2445

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

It's possible, but not wise, because the loaded users wouldn't reflect the actual state of the database : their list of works should contain all their works, and not only some of them. Modifying them could lead to unwanted deletes in the database.

I would rather load the works you're interested in, with their associated user :

Criteria c = session.createCriteria(Work.class, "work");
c.createAlias("work.user", "user");
c.setFetchMode("work.user", FetchMode.JOIN);
c.add(Restrictions.ne("work.name", "fck"));

Upvotes: 2

Related Questions