假设我有两个实体:
@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 说 “无法在此 ManagedType [A] 上找到具有给定名称 [b_id] 的属性”
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");
关于java - 如何使用 Criteria Query 只选择外键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35450072/