多对多查询 jpql

2022-09-01 09:25:31

我有以下麻烦。

有一个实体分销商与实体城镇的 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)所有在一个地区的分销商。我该怎么办?


答案 1
select distinct distributor 
from Distributor distributor  
join distributor.towns town 
join town.district district 
where district.name = :name

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


答案 2

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

@Entity
public class District {

  .....

   @ManyToOne
   private Town town;

   ....
}

推荐