【问题标题】:How to select just the foreign key value using Criteria Query?如何使用 Criteria Query 只选择外键值?
【发布时间】:2016-02-17 07:08:53
【问题描述】:

假设我有两个实体:

@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


    【解决方案1】:

    你需要加入B,然后获取id

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

    【讨论】:

    • 当信息存在于A本身时,为什么还要加入B?
    • 嗯,这不是选择“只是 fk”,而是在进行连接...同意 @msfk 为什么需要连接?应该如何抓住 fk 字段并在标准中使用它?
    • 如何在不使用 join 的情况下在 B 列上使用 in 子句。即仅在标准 api 的“in”子句中传递 id
    • 如果您只想按外键过滤,则不需要加入B。你可以做criteriaQuery.where(criteriaBuilder.equal(root.get("b").get("id"), &lt;idOfB&gt;)
    【解决方案2】:

    您可以在 A 类中声明外键,其中“B_ID”是表 A 中外键列的名称。然后您可以在上面的标准构建器示例中使用 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;
    

    【讨论】:

      【解决方案3】:

      如果您在查询中评估 FK 主键,则不一定需要加入,该主键存在于 A 实体中。

      root.get("b")
      

      此代码将通过其主键检索 FK。 例如你可以这样做:

      root.get("b").in(List.of(1,2,3,4));
      

      并且您有一个有效的谓词将 FK 值与此列表进行比较。

      【讨论】:

        猜你喜欢
        • 2020-10-14
        • 2013-11-09
        • 2014-09-02
        • 1970-01-01
        • 2013-05-10
        • 2013-05-27
        • 1970-01-01
        • 2016-06-26
        • 2011-08-25
        相关资源
        最近更新 更多