假设我有两个实体:
@Entity
public class A {
@Id
private int id;
@ManyToOne
private B b;
//more attributes
}
@Entity
public class B {
@Id
private int id;
}
因此,A的表有一个列为b_id
作为外键。
现在,我想根据其他领域的一些标准选择b_id
。如何使用条件查询执行此操作?
我尝试执行以下操作,抛出IllegalArgumentException,说"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);
你需要加入B
然后获取id
:
Path<Integer> bId = root.join("b").get("id");
您可以在类A中声明外键,其中“B_ID”是表A中外键列的名称。然后您可以在上面的criteriabuilder示例中使用root.get(“bId”)。我和你有同样的问题,这对我有用。
@Column(name="B_ID", insertable=false, updatable=false)
private int bId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "B_ID")
private B b;