CriteriaQuery join fetch not executed for @Embeddable with @OneToMany in Hibernate

Solution Verified - Updated

Environment

  • Red Hat JBoss Enterprise Application Platform (EAP) 6
  • Hibernate 4

Issue

  • A @OneToMany association exists from a "parent" to a "child" type through an @Embeddable
@Entity
public class ChildEntity implements Serializable {
    ...
}

@Embeddable
public class EmbeddedEntity implements Serializable {
    @OneToMany( cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "PARENT_GUID")
    private Set<ChildEntity> children;
    ...
}

@Entity
public class ParentEntity implements Serializable {
    @Id
    private String guid;

    @Embedded
    private EmbeddedEntity embedded;
    ...
}
  • A CriteriaQuery is constructed as follows (using hibernate-jpamodelgen properties)
CriteriaBuilder cb = entityManager.getCriteriaBuilder();

CriteriaQuery<ParentEntity> cq = cb.createQuery(ParentEntity.class);
Root<ParentEntity> root = cq.from(ParentEntity.class);
root.fetch(ParentEntity_.embedded).fetch(EmbeddedEntity_.children); // specify join fetch
cq.where(cb.equal(root.get(ParentEntity_.guid), "P1"));

TypedQuery<ParentEntity> typeQuery = entityManager.createQuery(cq);
  • The generated query omits the join fetch (as evident in looking at the generated SQL)
  • The association is not initialized and requires a subsequent query

Resolution

  • Use an HQL based query to perform the join fetch
  • The issue will be corrected in a future release

Root Cause

This is a This content is not included.defect1 in the Hibernate CriteriaQuery implementation

Diagnostic Steps

Enable Hibernate SQL trace

Components
Category

This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.