How to use JPA - EntityGraph to load only a subset of entity @Basic attributes?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 13:16:05

Actually, you are not doing anything wrong. Yet, you are missing an important piece of information from the Hibernate ORM User Guide (v5.0.x). In section 2.3.2 we find it:

fetch - FetchType (defaults to EAGER)

Defines whether this attribute should be fetched eagerly or lazily. JPA says that EAGER is a requirement to the provider (Hibernate) that the value should be fetched when the owner is fetched, while LAZY is merely a hint that the value be fetched when the attribute is accessed. Hibernate ignores this setting for basic types unless you are using bytecode enhancement. See the BytecodeEnhancement for additional information on fetching and on bytecode enhancement.

So: Even though you are giving a query hint to the em.find(..) method, it's up to the JPA provider - here: Hibernate - to decide if basic attributes will be fetched eagerly or not. In your case, the Employee entity only contains @Basic attributes.

For reference, and for a more context as well as a more detailed explanation, see also this tutorial. It covers differences between "javax.persistence.fetchgraph" and "javax.persistence.loadgraph"query hints and has example code which demonstrates the above behaviour for the JPA persistence provider Hibernate.

Side notes: I checked..

  • .. the Hibernate ORM User Guides 5.1, 5.2, and 5.3: All versions contain the very same statement on the default policy to ignore basic attributes.
  • .. the official JPA 2.1 specification document. On (PDF) page 117, in Section 3.7.4 we find:

    The persistence provider is permitted to fetch additional entity state beyond that specified by a fetch graph or load graph.

The latter quote from the JPA-spec backs the ORM User Guide that this it is ok to implement it that way.

My advice:

Look into BytecodeEnhancement as stated by the Hibernate ORM User Guide (see above).

Hope it helps.

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