Navigation method/s in criteria fetch joins in JPA 2.1

江枫思渺然 提交于 2021-01-27 17:10:48

问题


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.


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!