问题
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);
回答1:
You need to join to B
and then fetch the id
:
Path<Integer> bId = root.join("b").get("id");
回答2:
You can declare the foreign key in class A where "B_ID" is the name of the foreign key column in table A. And then you can root.get("bId") in your criteriabuilder example above. I have the same problem as you and this is working for me.
@Column(name="B_ID", insertable=false, updatable=false)
private int bId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "B_ID")
private B b;
来源:https://stackoverflow.com/questions/35450072/how-to-select-just-the-foreign-key-value-using-criteria-query