org.hibernate.QueryException: illegal attempt to dereference collection

HibernateHqlJpa 2.0DereferenceJpa 2.1

Hibernate Problem Overview


I am trying following hql query to execute

SELECT count(*) 
  FROM BillDetails as bd
 WHERE bd.billProductSet.product.id = 1002
   AND bd.client.id                 = 1

But it is showing

org.hibernate.QueryException: illegal attempt to dereference collection 
[billdetail0_.bill_no.billProductSet] with element property reference [product] 
[select count(*) from iland.hbm.BillDetails as bd where bd.billProductSet.product.id=1001 and bd.client.id=1]
	at org.hibernate.hql.ast.tree.DotNode$1.buildIllegalCollectionDereferenceException(DotNode.java:68)
	at org.hibernate.hql.ast.tree.DotNode.checkLhsIsNotCollection(DotNode.java:558)

Hibernate Solutions


Solution 1 - Hibernate

billProductSet is a Collection. As such, it does not have an attribute named product.

Product is an attribute of the elements of this Collection.

You can fix the issue by joining the collection instead of dereferencing it:

SELECT count(*) 
  FROM BillDetails        bd 
  JOIN bd.billProductSet  bps 
 WHERE bd.client.id       = 1
   AND bps.product.id     = 1002

Solution 2 - Hibernate

because billProduct is one to many mapping and there is many billProduct entity from one BillDetails entity you can't dereference it in query.you must join BillDetails model to billProduct and filter result with where cluase.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxrcwrnView Question on Stackoverflow
Solution 1 - HibernatekostjaView Answer on Stackoverflow
Solution 2 - HibernateJ.KView Answer on Stackoverflow