HQL Programming Standards
The Hibernate Query Language provides a more object-oriented approach to querying against the database. Joins can more clearly be indicated via navigation to the related foreign key, letting hibernate fill in the join when it constructs the SQL.
Here are some examples of creating and using queries. The convenience methods to create the query are available on any context managed object. That is, entities, change handlers, business components, maintenance classes, and the implementer extensions of any of them.
To select all algorithms with a given algorithm type:
AlgorithmType algorithmType = ... ;
Query query = createQuery("from Algorithm algorithm where " +
"algorithm.algorithmType = :algorithmType");
query.bindEntity("algorithmType", algorithmType);
List algorithms = query.list();
The above algorithms list will contain as elements the algorithms for that algorithm type.
To sort the above query by the algorithm's code/Id:
AlgorithmType algorithmType = ... ;
Query query = createQuery("from Algorithm algorithm where " +
"algorithm.algorithmType = :algorithmType");
query.bindEntity("algorithmType", algorithmType);
query.addResult("algorithm", "algorithm");
query.addResult("algorithmId", "algorithm.id");
query.orderBy("algorithmId", Query.ASCENDING);
List queryResults = query.list();
The above queryResults
list will contain as elements instances of the
interface QueryResultRow
. Each query result row will have two values,
keyed by "algorithm" and "algorithmId". The list will be ordered (on the database)
ascending by the algorithm's IDs.
Since HQL works with the entity's properties instead of the tables' column names, there may be
extra research required when writing queries. The source of the property information is
in the hibernate mapping document for each entity class- they are documents that exist
in the same package as the entity, have the same root file name as the entity's
interface, and end with .hbm.xml
. These files will give the list of
properties available for each entity that can be referenced when writing HQL.
More information can be found in the JavaDocs associated with the Query interface.