JPA: Query an embeddable List inside an entity

假如想象 提交于 2019-12-10 10:08:08

问题


I am trying to "extract" Embeddable classes based on some criterias from a list in an Entity. Either with the help of JPQL or Criteria API. I am not a pro at this, so please help me out. Been googling for 4 hours solid for an answer without any results.

These are the classes:

@Entity
public class PostOffice {

    @Id
    private Long id;

    @ElementCollection(fetch=FetchType.LAZY)
    @CollectionTable(joinColumns=@JoinColumn(name = "CARRIERID"))
    private List<PostalCarrier> carriers;

}


@Embeddable
public class PostalCarrier {

    @JoinColumn(name = "area")
    private Area area;

} 


@Entity
public class Area {

    @Id
    private int code;
}

So, basically what I'm trying to achieve is something like this.

TypedQuery<PostalCarrier> query = entityManager.createQuery("SELECT p.carriers FROM PostOffice p 
WHERE p.id = ?1 AND p.carriers.area.code = ?2", PostalCarrier.class);

    query.setParameter(1, postOfficeId);
    query.setParameter(2, areaCode);

I only want to get a list of the PostalCarriers at specific area code from a specific PostOffice. Any help is much appreciated! :)


I think I'm almost there, but keep getting the following error:

 Error compiling the query [SELECT h FROM PostOffice p INNER JOIN p.carriers h 
 WHERE p.id = ?1 AND h.area.code = ?2], line 1, column 71: unknown state or 
 association field [area] of class [com.test.PostalCarrier].

回答1:


You must make a join to the PostalCarrier. You can't access a property from a collection. Thus, postalcarrier.area isn't correct.

select postalcarrier from PostOffice p
inner join p.carriers postalcarrier
where p.id = :postOfficeId
and postalcarrier.area.code = :areaCode


来源:https://stackoverflow.com/questions/9137610/jpa-query-an-embeddable-list-inside-an-entity

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