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?