How to select only a foreign key value using a Criteria query?

Suppose I have two objects:

@Entity
public class A {

    @Id
    private int id;

    @ManyToOne
    private B b; 

    //more attributes
}

@Entity
public class B {

    @Id
    private int id;
}

So, the table for A has a column as b_ida foreign key.

Now I want to select only b_idon the basis of some criteria in other fields. How to do this using query criteria?

I tried to make and then throws an 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);
+4
source share
1 answer

You need to join B, and then choose id:

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

Source: https://habr.com/ru/post/1629110/


All Articles