hql find an entity by collection

Go To StackoverFlow.com


I have an Hibernate Entity named User, which has a Set<Book>

Book is another Entity having a String bookName;

I want to find all Users having an exact list of Books e.g.

List<Book> booksList = Arrays.AsList(
                           getBook("Tom Sawyer"), getBook("Christmas Carol"));

List<Book> usersHavingThoseBooks = getCurrentSession()
      .createQuery("from Users u inner join u.books b where b in (:booksList)")
      .setParameterList("booksList", booksList)

but it's not the solution. I've tried to query upon the id's of the books, which seem better but it doesn't give me only the users having the exact set of books.

e.g. if I have the following users in the database:

  • User(id=1, books={"Tom Sawyer", "Christmas Carol"})
  • User(id=2, books={"Tom Sawyer", "Alice in wonderland"})
  • User(id=3, books={"Tom Sawyer", "Christmas Carol", "Alice in wonderland"})
  • User(id=4, books={"Alice in wonderland", "Sql for dummies"})

the IN clause will return users 1, 2, 3, while I want only user 1 as he has exactly "Tom sawyer" and "Christmas carol".

The second query I need is to have users who have at least the books in the list I give as a parameter. e.g. all users having the two books 'Tom Sawyer' and 'Christmas Carol' plus all users having the two books and any other book (one or more)...

Does anyone have an idea how to achieve those two queries? Thanks!!

2012-04-03 23:44
by Aurelien


try this:

select u from Users u left join u.books b where b in (:booksList)

2012-04-04 00:53
by AndresQ
thanks but this doesn't work either, the issue I have is that the 'IN' clause sends me all users having at least one of the books, and not ALL the books I pass in the parameters - Aurelien 2012-04-04 01:08