Hibernate provides several ways to retrieve data from the database. We have seen the normal entity loading operations in our basic CRUD and we have seen several HQL and SQL query methods as well. The last one is the Hibernate Criteria Queries.
The ColdBox Hibernate Criteria Builder is a powerful object that will help you build and execute hibernate criteria queries in a fluent and dynamic manner. HQL is extremely powerful, but some developers prefer to build queries dynamically using an object-oriented API, rather than building query strings and concatenating them in strings or buffers. This is error prone, syntax crazy and sometimes untestable.
The ColdBox Criteria Builders offers a powerful programmatic DSL builder for Hibernate Criteria queries. It focuses on a criteria object that you will build up to represent the query to execute. The cool thing is that you can even retrieve the exact HQL or even SQL the criteria query will be executing. You can get the explain plans, provide query hints and much more. In our experience, criteria queries will make your life much easier when doing complicated queries.
As you will soon discover, they are fantastic but doing it the Java way is not that fun, so we took our lovely ColdFusion dynamic language funkyness and added some ColdBox magic to it.
userService.newCriteria().eq( "name", "luis" ).isTrue( "isActive" ).getOrFail();userService.newCriteria().isTrue( "isActive" ).joinTo( "role" ).eq( "name", "admin" ).asStream().list();userService.newCriteria().withProjections( property="id,fname:firstName,lname:lastName,age" ).isTrue( "isActive" ).joinTo( "role" ).eq( "name", "admin" ).asStruct().list();
You can see below some of the Hibernate documentation on criteria queries.