2

JPA: how to tell CriteriaQuery to fetch lazy properties? For example,

Student entity has description property that is declared lazy.

public class Student {

    @Basic(fetch=FetchType.LAZY)
    public String getDescription() {
           ...
    }
}

Retrieve all students eager fetching descriptions:

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Student> criteriaQuery = criteriaBuilder.createQuery(Student.class);
Root<Student> root = criteriaQuery.from(Student.class);
criteriaQuery.distinct(true);
TypedQuery<Student> query = em.createQuery(criteriaQuery);
List<Student> students = query.getResultList();

How to tell CriteriaQuerty to include student.description in query results?

For fetching lazy entities, I can use fetch

root.fetch("courses", JoinType.LEFT);
Dave
  • 759
  • 2
  • 9
  • 31
  • Use EntityGraph like the answer says. Also see https://stackoverflow.com/questions/37049358/hibernate-load-entities-with-fields-defined-at-runtime/37053402#37053402 – Neil Stockton Jun 21 '16 at 08:14

1 Answers1

1

You can use entity load graphs. This is fairly new and I think it's only supported in JPA2.1.

http://www.thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/

Till
  • 994
  • 5
  • 18
  • Entity graph in the article is a fetch plan for entity relations. Does it work for properties that are not entities, for example, clob? Thanks – Dave Jun 21 '16 at 03:45
  • EntityGraph is a fetch plan for ALL fields/properties! See the JPA spec! – Neil Stockton Jun 21 '16 at 08:09