7

The situation is like this:

I have an entity Book that holds a one-to-many relationship with Chapter.

Now if I try the query, "from Book book inner join book.chapters chapter where chapter.title like '%hibernate%'", it gives me the desired result.

But if I try, "from Book where book.chapters.title like '%hibernate%'", I get the error illegal attempt to dereference collection.

The thing is that I only want the collection of Book objects in return and not a collection of pair of Book and Chapter objects in return which I get with the former query.

Could someone help me understand?

skip
  • 12,193
  • 32
  • 113
  • 153

2 Answers2

12

chapters is a collection in books and so will not hold the property title (Collection.title). You need to join the chapters in order to include them in your query like your first example. If your chapters are mapped lazily you will only get a collection of Book's without the chapters loaded in them. So I would say, use your first query.

For further reading, have a look at the query HQL joins and performance fetching pages.

joostschouten
  • 3,863
  • 1
  • 18
  • 31
  • 1
    Even if Chapter entity was mapped lazily, why would it get only the collection of books with my former query? I think `select book from Book book inner join book.chapters chapter where chapter.title like '%hibernate%'` was what I should I tried instead in the first place. Many thanks for reply :) – skip Jun 19 '11 at 23:14
  • I added two links to my answer outlining the fetching strategies. – joostschouten Jun 20 '11 at 09:12
  • Thanks for the links, but i was getting book and chapter pairs in the result even when I was using LAZY for the fetching strategy. I was getting duplicate book objects though. Thanks for the links though :) – skip Jun 20 '11 at 14:48
2

You can likely do this with a subquery.

Something like

from Book book where not exists (from chapter where 
                   chapter.title like '%hibernate%' and chapter.book = book)

(Not tested ...)

Don Roby
  • 40,677
  • 6
  • 91
  • 113
  • 1
    Yes, that's probably fine. For some reason I thought you had something that was giving you more data than you wanted. – Don Roby Jun 19 '11 at 23:00
  • 1
    `select book from Book book inner join book.chapters chapter where chapter.title like '%hibernate%'` is working just fine for me. Many thanks for reply :) – skip Jun 19 '11 at 23:02
  • Sorry for the typo in my last comment, it was supposed to be title and hibernate. Yes, I just needed the duplicate objects to be removed and I wanted to use something like LinkedHashSet on the collection of books retrieved from the query. Thanks :) – skip Jun 19 '11 at 23:03
  • I think, `book.chapters.title` is not supported anymore and used to work only with older versions of hibernate. I am not sure about that fact though. – skip Jun 19 '11 at 23:07