Hibernate: Select entities where collection contains all of the specified valus

前端 未结 3 1705
闹比i
闹比i 2020-12-16 06:31

I need assistance with a tricky hibernate query problem. I have the following entities:

public class Book {
   private String bookId;
   private String autho         


        
3条回答
  •  醉梦人生
    2020-12-16 06:54

    The accepted answer from JB Nizet is good but will not work if your collection can contain duplicates (might be a valid reason for that, probably not with the tag example though).

    Lets say the collection for some books can contain duplicate tags with the same name "MyTag". Then a search for the Tags "MyTag", "YourTag" could return books that have 2 "MyTag" tags but no "YourTag" tag.

    select b from Book b where :numberOfTags = (select count(distinct tag.tagName) from Book b2 inner join b2.tags tag where b2.id = b.id and tag.tagName IN (:tagNames)) 
    

    As I said nothing wrong with the accepted answer but if you need to support duplicates in the collection then you need to add count(distinct tag.name)

提交回复
热议问题