JPA 2 Criteria Fetch Path Navigation

前端 未结 6 665
我寻月下人不归
我寻月下人不归 2020-12-08 14:38

With JPA 2 Criteria Join method I can do the following:

    //Join Example (default inner join)
    int age = 25;
    CriteriaBuilder cb = entityManager.getC         


        
6条回答
  •  抹茶落季
    2020-12-08 15:05

    Beginning with JPA 2.1, dynamic entity graphs can be used for fetching in criteria queries, while using join() instead of fetch(). From the example in the question:

    //Join Example (default inner join)
    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery c = cb.createQuery(Team.class);
    Root t = c.from(Team.class);
    Join p = t.join(Team_.players);
    c.select(t).where(cb.equal(p.get(Player_.age), age));
    TypedQuery q = entityManager.createQuery(c);
    List result = q.getResultList();
    

    If this:

    TypedQuery q = entityManager.createQuery(c);
    

    is replaced with this:

    EntityGraph fetchGraph = getEntityManager().createEntityGraph(Team.class);
    fetchGraph.addSubgraph(Team_.players);
    TypedQuery q = entityManager.createQuery(c).setHint("javax.persistence.loadgraph", fetchGraph);
    

    then all players will be eager fetched.

提交回复
热议问题