Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 5 and Typed Criteria Queries (JPA2)

Questions:

1) If I upgrade from Hibernate 4.x to Hibernate 5.x, can I still use the "old" Criteria Queries, or only the new Typed JPA2 Criteria Queries? Is the old one deprecated, or can I use both side by side?

2) Did I understand correctly that the new Typed Criteria forces me to create a second class for each Entity class I have, thus duplicating the number of classes? Am I supposed to create these classes by hand? If not, how? Rant: Having to duplicate classes seem bizarre, so I must be misunderstanding it somehow? Isn't that overkill and unnecessarily complicated?

like image 987
MarcG Avatar asked Mar 06 '16 07:03

MarcG


People also ask

What is Hibernate Criteria query?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

Is Criteria API deprecated?

The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kinds of filtration rules and logical conditions. Since Hibernate 5.2, the Hibernate Criteria API is deprecated, and new development is focused on the JPA Criteria API.


1 Answers

  1. No, the old criteria API is not deprecated. Just look at the javadoc: there is no deprecation warning. But I would recommend sticking to the standard JPA API, and not using the standard JPA API mixed with the proprietary Hibernate API.

  2. No, it doesn't force you. You can still use String identifiers. But if type-safety is the goal, using the metamodel classes is strongly recommended.

Of course you don't need to generate these by hand. They're generated by an annotation processor, from your entity classes and their mapping annotations. You may find it bizarre, but it's much safer to use root.get(MyEntity_.firstName) than root.get("firstName"): a typo is detected at compilation time, and if you refactor the field to firstname, the compiler will generate an error instead of letting you use the old "firstName" string identifier.

I still find JPQL queries much simpler to write, understand and maintain though, and would only use the criteria API when a dynamic query has to be generated based on multiple... criteria. Use automated tests to check if the queries are correct. Do the same, even with the criteria queries, BTW.

like image 55
JB Nizet Avatar answered Sep 29 '22 22:09

JB Nizet