Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select just the foreign key value using Criteria Query?

Suppose I have two entities as:

@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 is having a column as b_id as the foreign key.

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

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);
like image 836
Anmol Gupta Avatar asked Feb 17 '16 07:02

Anmol Gupta


1 Answers

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

Path<Integer> bId = root.join("b").get("id");
like image 146
wero Avatar answered Oct 17 '22 01:10

wero