Everything You Need To Know About Hibernate HQL
The problem with Hibernate HQL is that it looks exactly like SQL. The one thing that held me back the longest on understanding how it works is that it's NOT SQL. You're not querying SQL tables, you're querying objects and their variables.
As an example, a self referencing object:
The entity class contains the initialization of 'ID' and 'versionID' which are both type LONG.
-
<hibernate -mapping>
-
<class name="vitalvinyl.model.media.Genre" table="`GENRE`">
-
<id name="ID" column="`ID`" type="long" unsaved-value="-1">
-
<generator class="native"/>
-
</id>
-
<version name="versionID" column="`VERSIONID`" type="long" unsaved-value="negative"/>
-
<property name="name" column="`NAME`" type="string" not-null="true" unique="true"/>
-
<property name="description" column="`DESCRIPTION`" type="string"/>
-
<property name="dance" column="`DANCE`" type="boolean"/>
-
<property name="hiphop" column="`HIPHOP`" type="boolean"/>
-
<many -to-one name="parent" column="`PARENTID`" class="vitalvinyl.model.media.Genre"/>
-
</class>
-
</hibernate>
You can see how Genre refers to itself. This is to create a hierarchy of sub-genres.
Now, let's say we want to find all subgenres with a parent ID of 15.
-
String sQuery = "select g \n" +
-
"from Genre as g \n" +
-
"join g.parent as p \n" +
-
"where p.ID = 15";
Notice that I'm referenceing the Genre object's variable name 'parent' with the associated Genre alias 'g.' Pay attention to the capitalization. This is the major difference from SQL that no HQL tutorials I've read have taken the time to mention.
So, in conclusion, USE HQL TO REFERENCE OBJECT HIERARCHIES, NOT TABLES. ALSO, PIE IS REALLY GOOD.