Hibernate: how to look for objects in a Set
I am trying to figure out开发者_开发问答 what the best way to write the HQL statement for the following scenario is:
I have a class Book which one of its properties is of the type Set{Author} (actually meant to type inequality signs here). The class Author has properties such as id, name, etc.
Now my DAO method gets "Set authors" as a parameter. For this method I want to write an HQL query so I could get all the Books that at least one of their Authors is found in authors.
What is the best way to accomplish this?
Pay attention that both the Set property in the class Book and the Set parameter that is being passed on to the method may include multiple Authors.
Thanks!
EDIT
Had I had only one author per Book, I could have done something like:
FROM Book as book WHERE book.author IN (:authors)
However this does not work when each Book has a Set of Authors.
Have you tried
select distinct b from Book b join b.authors a where a in (:authors)
Note that if you need join fetch
, it should be specified separately:
select distinct b from Book b join b.authors a left join fetch b.authors
where a in (:authors)
is there a particular reason why you don't want to use Hibernate's Criteria to do this?
Set<Author> authors = [ your set of Author Objects ]
Criteria crit = createCriteria(Book.class)
.add( Restrictions.in( "author", authors ) );
List<Book> books = crit.list();
You have to make one hql query by author passed as a parameter.
For each author, the HQL will look like :
from Book as book
join book.authors author
where author = < one_of_my_author_passed_as_parameter >
And then, you add the result of each query to the main result list.
精彩评论