Mercer
Mercer

Reputation: 9986

Query a database table using a foreign key ( where) using Hibernate

i m new to hibernate, so the question might look stupid.

I have the two tables:

Application:

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

Compilation:

@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;
....

and i want to get a list of Compilation that matches a given Application.

i did the following query:

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

But it is not working.

Error:

Caused by: org.hibernate.QueryException: could not resolve property: Application of: xx.xx.xx.xx.xx.Compilation [FROM xx.xx.xx.xx.xx.Compilation c WHERE c.Application.id = :applicationId] at org.hibernate.QueryException.generateQueryException(QueryException.java:137) at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158) at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:126) at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:88) at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190) at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301) at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236) at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800) at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)

Upvotes: 2

Views: 5658

Answers (1)

Learner
Learner

Reputation: 21393

Your query should be :

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

You have created an alias c for entity, Hibernate tries to check the Compilation, now you can access the properties of the Compilation entity. Now the property in Compilation class is application and this application property represents the Application which has the field appID

Upvotes: 5

Related Questions