本文介绍了如何使用条件查询仅选择外键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个实体:

@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.

So, the table for A is having a column as b_id as the foreign key.

现在,我想根据其他字段上的某些条件仅选择b_id.如何使用条件查询来做到这一点?

Now, I want to select just the b_id based on some criteria on other fields. How can I do this using criteria query?

我尝试执行以下操作,该操作引发IllegalArgumentException说"Unable to locate Attribute with the given name [b_id] on this ManagedType [A]"

I tried doing following which throws IllegalArgumentException saying "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:

You need to join to B and then fetch the id:

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

这篇关于如何使用条件查询仅选择外键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:41