如何使用 Criteria Query 仅选择外键值?

Anm*_*pta 6 java jpa criteria-api

假设我有两个实体:

@Entity
public class A {

    @Id
    private int id;

    @ManyToOne
    private B b; 

    //more attributes
}

@Entity
public class B {

    @Id
    private int id;
}
Run Code Online (Sandbox Code Playgroud)

因此,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);
Run Code Online (Sandbox Code Playgroud)

wer*_*ero 7

您需要加入B并获取id

Path<Integer> bId = root.join("b").get("id");
Run Code Online (Sandbox Code Playgroud)

  • 当信息存在于 A 本身时,为什么需要加入 B? (7认同)
  • 好吧,这不是选择“只是 fk”,而是正在执行连接...同意@msfk 为什么需要连接?应该如何抓住 fk 字段并在标准中使用它? (2认同)

小智 6

您可以在 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;
Run Code Online (Sandbox Code Playgroud)