问题
While using fetch joins in JPA criteria, there is no navigation method can be seen. Given below an example.
Root<UserTable> root = criteriaQuery.from(entityManager.getMetamodel().entity(UserTable.class));
Fetch<UserTable, StateTable> fetch = root.fetch(UserTable_.stateTable, JoinType.INNER);
To navigate through the entity in question, this Fetch
type is required to be cast to a join like as follows.
Join<UserTable, StateTable> join = (Join<UserTable, StateTable>) root.fetch(UserTable_.stateTable, JoinType.INNER);
The navigation method get()
is available after this cast just like,
join.get(UserTable_.firstName);
Is this type cast portable (while it works on EclipseLink (2.5.1) and Hibernate (4.3.5))? Is there any other ways to do the same? Is there any specific reason as to why criteria fetch joins do not support a navigation method?
UPDATE : (I would still consider this to be just a partial answer. Hence, not written in the answer section)
This is very well spotted on here by James as to why a navigation method in FETCH JOIN
(including aliasing in JPQL) is highly discouraged and not recommended especially in OneToMany
relationships (and consequently not directly provided/supported in FETCH JOIN
s):
EclipseLink allows you to use an alias on a
JOIN FETCH
. This support was intended forOneToOne
andManyToOne
relationships, to avoid having to join it twice just to get an alias, as well as to allow using it in anORDER BY
or in other ways that would not filter the results and alter how the objects are built. But, there is nothing stopping you from using it with aOneToMany
to filter the contents of the fetchedOneToMany
results.
You may want to read up the entire blog with the given examples instead. To my experience, Hibernate (at latest versions) also allows us to do this.
In general, I personally do not use aliasing in OneToMany
relationships to navigate through the target entity (the one which has the foreign key) that indeed should not be needed in real projects at best but it is required in OneToOne
and/or ManyToOne
.
回答1:
You may call
Join<UserTable, StateTable> join = root.join("prop", JoinType.INNER);
See here: http://docs.oracle.com/javaee/6/api/javax/persistence/criteria/From.html#join(java.lang.String,%20javax.persistence.criteria.JoinType)
来源:https://stackoverflow.com/questions/24104531/navigation-method-s-in-criteria-fetch-joins-in-jpa-2-1