多对一搜索查询

时间:2013-06-30 00:17:05

标签: java java-ee jpa persistence many-to-one

我在JPA中遇到一个关于多对一关系的问题。我现在遇到的问题是使用where子句来获取数据。

Skills上课:

    @Id
    private long skillsID;
    @Basic
    private String longDescription;
    @Basic
    private String shortDescription;
    @Basic
    private String colOrder;
    @Basic
    private String isActive;
    @Basic
    private String changeDate;
    @ManyToOne(fetch=FetchType.EAGER)
    private Category category;

第二个实体是:

Category上课:

    @Id
    private long categoryID;
    @Basic
    private String name;
    @Basic
    private String colOrder;
    @Basic
    private String isActive;
    @Basic
    private String changedDate;
    @OneToMany(mappedBy = "category")
    private Collection<Skills> skills;

所以在JPA中,当我执行以下代码时,它会抛出异常,如:

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 

Exception Description: Problem compiling [SELECT s.longDescription  from Skills s, Category c  where s.categoryID =  c.categoryID]. 

[57, 69] The state field path 's.categoryID' cannot be resolved to a valid type.

JPA代码是:

Query q = em .createQuery("SELECT s.longDescription  from Skills s, Category c "+
"where s.categoryID =  c.categoryID");

那么,如何根据外键从Skills获取数据到Category

1 个答案:

答案 0 :(得分:1)

categoryID实体中没有字段Skills

只需使用category中的Query字段:

Query q = em .createQuery("SELECT s.longDescription from Skills s, Category c " +
                          "WHERE s.category =  c");