多对多查询jpql

时间:2013-09-03 12:37:52

标签: java jpa jpa-2.0 jpql

我遇到了麻烦。

有一个实体分销商与实体城镇的ManyToMany关系连接:

@Entity
public class Distributor{

   @ManyToMany
   @JoinTable( name = "GS_DISTRIBUTOR_TOWN",
           joinColumns = @JoinColumn(name = "CD_DISTRIBUTOR"),
           inverseJoinColumns = @JoinColumn(name = "CD_TOWN") )
   private List<Town> towns;

   ....
}

然后实体城镇也与区域有关

@Entity
public class Town{

   @ManyToMany(mappedBy="towns")
   private List<Distributor> distributors;

   @ManyToOne
   private District district;

   ....
}

现在我必须过滤(使用jpql)所有分区中的经销商。 我该怎么办?

2 个答案:

答案 0 :(得分:31)

select distinct distributor 
from Distributor distributor  
join d.towns town 
join t.district district 
where district.name = :name

请参阅:https://en.wikibooks.org/wiki/Java_Persistence/JPQL

答案 1 :(得分:0)

首先,在实体Town中,@ Manytoone的关系映射不正确。 应该是:

@Entity
public class District {

  .....

   @ManyToOne
   private Town town;

   ....
}