使用Hibernate使用外键(where)查询数据库表

时间:2014-09-24 13:34:30

标签: spring hibernate jpa

我是hibernate的新手,所以问题可能看起来很愚蠢。

我有两张桌子:

应用:

@Entity
@Table
public class Application extends BaseSimpleEntity {
    @Column(nullable = false)
    private String appID;
    @OneToOne(cascade = CascadeType.ALL)
    @Searcheable
    private LocalizedString name;
...

汇编:

@Table
@Entity
public class Compilation extends BaseSimpleEntity {

    @Column(nullable = false)
    private String uid;
    @ManyToOne
    private Application application;
    @Column
    private DateTime creationDate;
    @Column
    private DateTime finishDate;
    @Column
    private String path;
....

我希望得到一个与给定应用程序匹配的编译列表。

我做了以下查询:

@Query("FROM Compilation c WHERE c.Application.id = :applicationId")
List<Compilation> findValidCompialiton(@Param("applicationId") Long applicationId);

但它没有用。

错误:

  

引起:org.hibernate.QueryException:无法解析属性:   应用程序:xx.xx.xx.xx.xx.Compilation [FROM   xx.xx.xx.xx.xx.Compilation c WHERE c.Application.id =:applicationId]     在   org.hibernate.QueryException.generateQueryException(QueryException.java:137)     在   org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)     在   org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)     在   org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)     在   org.hibernate.engine.query.spi.HQLQueryPlan。(HQLQueryPlan.java:126)     在   org.hibernate.engine.query.spi.HQLQueryPlan。(HQLQueryPlan.java:88)     在   org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)     在   org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)     在   org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)     在   org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)     在   org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)

1 个答案:

答案 0 :(得分:5)

您的查询应该是:

@Query("FROM Compilation c WHERE c.application.appID = :applicationId")

您已为实体创建别名c,Hibernate会尝试检查Compilation,现在您可以访问Compilation实体的属性。现在Compilation类中的属性为application,此application属性代表Application字段appID