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

问题描述 投票:4回答:2

假设我有两个实体:

@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);
java jpa criteria-api
2个回答
4
投票

你需要加入B然后获取id

Path<Integer> bId = root.join("b").get("id");

0
投票

您可以在类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;
© www.soinside.com 2019 - 2024. All rights reserved.