How to perform a join fetch in JPA Criteria without unchecked casting?

邮差的信 提交于 2021-01-28 06:30:15

问题


I need to do a JOIN FETCH in JPA Criteria using a static metamodel, however I'm at a loss on how to do it without getting an unchecked exception warning.

Suppose we have a Thing entity with a lazily-initialized Other entity inside it. I want to retrieve Things with fetched Others, where other.someField="someValue". This is roughly how I would do it:

public List<Thing> getThings() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Thing> cq = cb.createQuery(Thing.class);
    Root root = cq.from(Thing.class);

    // This gives an unchecked cast warning:
    Join<Thing, Other> other = (Join<Thing, Other>) root.fetch(Thing_.other);

    cq.select(root).where(cb.equal(other.get(Other_.someField), "someValue"));

    return em.createQuery(cq).getResultList();
}

However, since the Join and Fetch interfaces have nothing in common, I get an "unchecked cast" warning. I would like to get rid of that warning (without using @SuppressWarnings).

I suppose I could do it this way:

cb.equal(root.get(This_.THING).get(Other_.SOMEFIELD), "someValue"))

But I'm doubtful whether it's better, seeing as I'm operating on Strings here (so no type safety).

What is a cleaner way of achieving the above?


回答1:


Fetch method is not supposed for creating JPA joins. In JPA join is used to create where conditions, not for loading data. This is different from native SQL. For JOIN use:

Join<Thing, Other> other = root.join(Thing_.other);

Independently collection can be loaded with or without calling join():

root.fetch(Thing_.other);


来源:https://stackoverflow.com/questions/55450323/how-to-perform-a-join-fetch-in-jpa-criteria-without-unchecked-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!