简体   繁体   中英

Hibernate criteria filter inner collection

I have the next classes/tables:

User

  • id
  • name
  • works // list of work

Work

  • id
  • name
  • user_id

And the following code:

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

returns a list of User s 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 Work s where name ='fck'?

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM