1

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?

Daniel Frąk
  • 110
  • 7

1 Answers1

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);
Peter Šály
  • 2,848
  • 2
  • 12
  • 26
  • The problem is using this method, the resulting query will produce two joins : `Root root = query.from(Thing.class); SetJoin othersJoin = root.join(Thing_.others); root.fetch(Thing_.others);` will produce: `SELECT foo_0.id, bar_1.id, bar_1.foo_id FROM foo AS foo_0 INNER JOIN bar AS bar_0 ON foo_0.id = bar_0.foo_id INNER JOIN bar AS bar_1 ON foo_0.id = bar_1.foo_id` Depending on the number of records, the query can increase drastically. In my case it was 10 times longer. – Calcimicium Aug 19 '22 at 15:06