uniqueResultOptional fails for Query created from CriteriaQuery

Description

When using the CriteriaQuery API and invoking a query using the uniqueResultOptional() methodthrows a QueryException for a Named parameter not set. This exception is not thrown if the JPA method getResultList() is used instead.

After debugging this I determined the root cause is the Query returned by Session.createQuery(CriteriaQuery) is a CriteriaQueryTypeQueryAdapter. It overrides the methods for getSingleResult() and getResultList() to invoke the corresponding methods on its jpqlQuery method, a fully populated QueryImpl. Hibernate-specific methods, including uniqueResultOptional() are not overridden by CriteriaQueryTypeQueryAdapter, and thus the corresponding methods are not invoked on the jpqlQuery member.

Here is a sample source that causes the problem:

And a stack trace snippet illustrating the issue:

Environment

None

Activity

Show:
Andrea Boriero
July 15, 2016, 4:21 PM

should not

return a

instead of

?

Will Darby
July 15, 2016, 7:23 PM

As one would expect, the same problem arises with scroll(), and presumably the corresponding method from org.hibernate.query.Query#stream(), which uses scroll() under the covers.

If Session#createQuery(CriteriaQuery) does not return a org.hibernate.query.Query then it cannot be used as a replacement for the Criteria API, which provides a method for scrolling through results using a cursor. This will force Hibernate 4.x based applications to migrate to the HQL interface instead.

Will Darby
July 18, 2016, 4:29 PM

My bad - I can use javax.persistence.Query#unwrap( org.hibernate.query.Query ) to get the underlying query and use all Hibernate APIs. This seems clearer since only TypedQuery methods are @Override by CriteriaQueryTypeQueryAdapter, so I agree that Session#createQuery(CriteriaQuery) should return a javax.persistence.TypedQuery.

Steve Ebersole
July 18, 2016, 4:51 PM

org.hibernate.query.Query is a javax.persistence.TypedQuery

Andrea Boriero
July 18, 2016, 6:36 PM


when you have time can you give a look at https://github.com/hibernate/hibernate-orm/pull/1481 ?

Assignee

Andrea Boriero

Reporter

Will Darby

Fix versions

Labels

None

backPortable

None

Suitable for new contributors

None

Requires Release Note

None

Pull Request

None

backportDecision

None

Components

Affects versions

Priority

Major
Configure