Suppose I have two entities as:
@Entity
public class A {
@Id
private int id;
@ManyToOne
private B b;
//more attributes
}
@Entity
public class B {
@Id
private int id;
}
So, the table for A is having a column as b_id
as the foreign key.
Now, I want to select just the b_id
based on some criteria on other fields. How can I do this using criteria query?
I tried doing following which throws IllegalArgumentException saying "Unable to locate Attribute with the given name [b_id] on this ManagedType [A]"
CriteriaQuery<Integer> criteriaQuery = criteriaBuilder.createQuery(Integer.class);
Root<A> root = criteriaQuery.from(A.class);
Path<Integer> bId = root.get("b_id");
//building the criteria
criteriaQuery.select(bId);
You need to join to B
and then fetch the id
:
Path<Integer> bId = root.join("b").get("id");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With