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

ⅰ亾dé卋堺 提交于 2021-02-08 13:52:54

问题


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);

回答1:


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

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



回答2:


You can declare the foreign key in class A where "B_ID" is the name of the foreign key column in table A. And then you can root.get("bId") in your criteriabuilder example above. I have the same problem as you and this is working for me.

@Column(name="B_ID", insertable=false, updatable=false)
private int bId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "B_ID")
private B b;


来源:https://stackoverflow.com/questions/35450072/how-to-select-just-the-foreign-key-value-using-criteria-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!