简体   繁体   English

hql 通过集合查找实体

[英]hql find an entity by collection

I have an Hibernate Entity named User , which has a Set <Book >我有一个名为User的 Hibernate 实体,它有一个Set <Book >

Book is another Entity having a String bookName; Book是另一个具有String bookName 的实体;

I want to find all Users having an exact list of Books eg我想找到所有具有确切书籍列表的用户,例如

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)
      .list();

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.我试图查询书籍的 ID,这看起来更好,但它并没有给我拥有确切书籍集的用户。

eg if I have the following users in the database:例如,如果我在数据库中有以下用户:

  • User(id=1, books={"Tom Sawyer", "Christmas Carol"}) User(id=1, books={"汤姆索亚", "圣诞颂歌"})
  • User(id=2, books={"Tom Sawyer", "Alice in wonderland"}) User(id=2, books={"汤姆索亚", "爱丽丝梦游仙境"})
  • User(id=3, books={"Tom Sawyer", "Christmas Carol", "Alice in wonderland"}) User(id=3, books={"汤姆索亚", "圣诞颂歌", "爱丽丝梦游仙境"})
  • User(id=4, books={"Alice in wonderland", "Sql for dummies"}) User(id=4, books={"爱丽丝梦游仙境", "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". IN 子句将返回用户 1、2、3,而我只想要用户 1,因为他正好有“Tom sawyer”和“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.我需要的第二个查询是让用户至少拥有我作为参数给出的列表中的书籍。 eg 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!!谢谢!!

try this:试试这个:

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

select u from Users u left join u.books b where b in (:booksList) group by u.id having count(u.id) = :count") select u from Users u left join u.books b where b in (:booksList) group by u.id with count(u.id) = :count")

where count - booksList.size()其中计数 - booksList.size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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