2

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 JOINs):

EclipseLink allows you to use an alias on a JOIN FETCH. This support was intended for OneToOne and ManyToOne relationships, to avoid having to join it twice just to get an alias, as well as to allow using it in an ORDER 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 a OneToMany to filter the contents of the fetched OneToMany 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.

Community
  • 1
  • 1
Tiny
  • 27,221
  • 105
  • 339
  • 599

1 Answers1

-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)

win_wave
  • 1,498
  • 11
  • 9