javaJPA+Hibernate: CriteriaQuery not loading eager ManyToOne relation

I'm having some trouble to make CriteriaQuery load ManyToOne relationships without
telling it explicitly and it seems very strange having to replicate my entity annotations
in the query to make this work:

  • I have an application using JPA + Hibernate (hibernate-jpa-2.0-api)

  • My entity Computer, apart from other fields contains the relationship:

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "employee", nullable = false)
    private Employee employee = null;

  • As far as I know, when I load a Computer entity, the Employee related to it should be loaded in the same query automatically but, if loading a Computer using CriteriaQuery, it does not work that way. That is, when I create a javax.persistence.criteria.CriteriaQuery and execute it, I can
    see two different queries:

    • one to fetch the Computer
    • another one to fetch the Employee (even before I use it..that is, it seems to be loading this entity because of the eager annotation)

From my point of view, this should be done in the same query but don't know what to do to make this work. If I add a ".fetch("employee")" to the criteriaquery it works but that way I'm replicating the configuration in the entity in my query and, from the point of view of the maintenance, this is not a solution.

Is this behavior normal? Can it be modified?


FetchType.EAGER means that the linked entity must be fetched at same time as root entity, but the jpa-specifications don't say anything about the strategy to do this (i.e. using one or two queries is a choice left to persistence provider implementation).

Hibernate provide the annotation @Fetch(FetchMode.JOIN) that indicate to hibernate to fetch both entities with one single query, so you can use that to achieve what need (but it is not a standard JPA annotation)

Related Articles
You Might Also Like