You can navigate associations in criteria queries in several ways:
Dot notation for many-to-one relationships ONLY
Helper methods to create inner criterias or joins: createCriteria(), joinTo()
This type of navigation is the easiest but ONLY works with many-to-one
associations. Let's say you have a User entity with a Role and the Role has the following properties: id, name, slug
and you want to get all users that have the role slug of admin
and are active. Then you could do this:
You can also use the joinTo()
method, which previously was called createAlias()
to create joins to related associations. Let's check out the method signature first:
The arguments can be further explained below:
associationName
: This is the name of the property on the target entity that is the association
alias
: This is the alias to assign it so you can reference it later in the criterions following it
joinType
: By default it is an inner join. The available joins are: INNER_JOIN, FULL_JOIN, LEFT_JOIN
withClause
: This is the criterion (so it's a restriction) to be added to the join condition, basically the ON
clause.
The last journey to query on associations is to pivot the root entity of the criteria to an association. This means that you will create a new criteria object based on the previous criteria, but now the target entity is the one you assign. PHEW! That's a mouthful. Basically, it's a nice way to traverse into the join and stay in that entity.
This is accomplished via the createCriteria()
method or the nice dynamic alias: with{entity}
() method.
The arguments can be further explained below:
associationName
: This is the name of the property on the target entity that is the association
alias
: This is the alias to assign it so you can reference it later in the criterions following it
joinType
: By default it is an inner join. The available joins are: INNER_JOIN, FULL_JOIN, LEFT_JOIN
withClause
: This is the criterion (so it's a restriction) to be added to the join condition, basically the ON
clause.
Now remember that you are rooting the criteria in this association, so you can't go back to the original entity properties.