How could I write the following JPQL query using Criteria API?
" select a from A a left join fetch a.bs b where b.i like 'X%' "
A-to-B is a One-To-Many relationship where A and B is like following:
@Entity
public class A {
@OneToMany(cascade={CascadeType.PERSIST})
private Set<B> bs = new HashSet<B>();
//...
}
@Entity
public class B {
private String i;
//...
}
I tried the foolowing:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = cb.createQuery( A.class );
Root<A> aRoot = cq.from( A.class );
Fetch<A, B> bs = aRoot.fetch(A_.bs, JoinType.LEFT);
cq.where(cb.like(what_do_i_do_here, "X%"));
cq.select(aRoot);
I need to get all those A
s along with its associated B
s where the i
value of the associated B
s start with an "X"
.
EDIT:
If I try the method given at How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery? I incorrectly get 2 A
s in result while I should get just 1 A
whose associated B_.i has the value that starts with "X".
I got the issue resolved using the following code:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<A> cq = builder.createQuery( A.class );
Root<A> root = cq.from( A.class );
Join<A, B> bs = (Join<A, B>) root.fetch(Guide_.students, JoinType.LEFT);
cq.where(builder.like(bs.get(B_.i), builder.parameter(String.class, "i")));
cq.select(root);
TypedQuery<A> query = em.createQuery(criteria).setParameter("i", "X%");
List<A> as= query.getResultList();
for (A a: as) {
System.out.println(a);
}