two - jpa expression example

JPA-style Criteria/CriteriaBuilder queries from Hibernate Session (1)

We have the same dilemma in our project. The project is really complicated: 90% of entities are generated dynamically; there is implemented API level above Hibernate criteria API, heavy DAO and service layer, that is very wide used; our hibernate version is patched many times to support specific functionality (like START WITH/CONNECT BY, ARRAY type in oracle and so on); postgresql and oracle are used both, alternatively etc.

The new JPA API would be very useful for us. We need ability to use functions at Criteria API (not HQL) level (like NVL/coalesce for some sort of performance reasons, substring, trim and so on). Moreover we need Hibernate Envers which is available only for "EntityManager" JPA implementation.

Unhappily according to our research result there is no ability to use JPA Criteria API from native Hibernate at all. Envers can not be used too. The Hibernate project is continually evolving and gaining new features. Migrating to new hibernate versions is very complicated task for us. And we are very concerned about inability to use many new features of new versions after migration and grow with this basic framework.

Therefore we consider two possible ways for us: use SQLCriterion with own implementation of Expressions (resolve column names with CriteriaQuery and translate to SQL) or migration to "EntityManager" / CriteriaBuilder. Second way looks like unavoidable. But the migration to JPA implementation brings many hidden problems which ruins our project.

If we'll choose migration and it will be useful, I'll leave here what problems we will struggle with in this activity.

I have an application that uses Hibernate 4.x, and it is currently using the native Hibernate APIs (meaning that I have a SessionFactory and Sessions). I just noticed that the existing Criteria API is deprecated in favor of JPA's (superior) Criteria API:

Hibernate offers an older, legacy org.hibernate.Criteria API which should be considered deprecated. No feature development will target those APIs. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery.

I don't want to have to convert my application over to using EntityManager directly (even though it's easy to get a Hibernate Session from there) because we have a large amount of custom Hibernate configuration logic that will need to be replaced. Despite that, I definitely want to start using the JPA Criteria APIs, since the old APIs are deprecated (and will presumably disappear at some random point in the future, if past Hibernate releases are any indication) and they also provide much better type safety.

How can I use the new CriteriaQuery/CriteriaBuilder API, if I'm using SessionFactory/Session?