JPA 2 Criteria Fetch Path Navigation

2022-01-20 00:00:00 fetch java jpa jpa-2.0

使用 JPA 2 Criteria Join 方法,我可以执行以下操作:

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

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

我怎样才能用 fetch 方法做同样的事情,我希望 Fetch 接口有路径导航的 get 方法,但它没有:

How can I do the same with fetch method, I expected that Fetch interface had get method for path navigation but it doesn't:

    //Fetch Join Example

    int age = 25;
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Team> cq = cb.createQuery(Team.class);
    Root<Team> t = cq.from(Team.class);
    Fetch<Team,Player> p = t.fetch(Team_.players);
    cq.where(cb.equal(p.get(Player_.age), age)); //This leads to compilation error there is no such method get in interface Fetch
    TypedQuery<Team> q = entityManager.createQuery(cq);
    List<Team> result = q.getResultList();

根据 Hiberante Documentation fetch 返回一个错误的 Join 对象.http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/querycriteria.html#querycriteria-from-fetch

According to Hiberante Documentation fetch returns a Join object which is wrong. http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/querycriteria.html#querycriteria-from-fetch

推荐答案

同意你关于该方法的观点,以及你希望它允许你所说的事实.另一种选择是

Agree with you about that method, and the fact that you would expect it to allow what you say. Another option would be

Join<Team, Player> p = t.join(Team_.players);
t.fetch(Team_.players);
c.select(t).where(cb.equal(p.get(Player_.age), age));

即执行一个 join(),为其添加一个 fetch(),然后使用该连接.这是不合逻辑的,只会增加 JPA 标准的不雅性,但无论如何,应该是一种解决方法

i.e do a join(), add a fetch() for it, and then make use of the join. This is illogical and only adds to the inelegant nature of JPA Criteria, but anyway, ought to be a workaround

相关文章