JPA:如何在多对多关系中给定另一个实体的ID来获取一个实体的子代?

时间:2019-04-12 07:10:05

标签: java jpa

从实体到自身,我与多对多的关系。

@Entity
@Table(name = "MERCHANTS")
public class Merchant {

  @Id
  @GeneratedValue
  private long id;

  @OneToMany(mappedBy = "merchant", fetch = FetchType.EAGER)
  @Fetch(FetchMode.SELECT)
  private List<Service> services;

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(name = "SUB_MERCHANTS", joinColumns = { @JoinColumn(name = "merchant_id") }, inverseJoinColumns = { @JoinColumn(name = "submerchant_id") })
  private final Set<Merchant> submerchants = new HashSet<>();

  @ManyToMany(mappedBy = "submerchants")
  private final Set<Merchant> merchants = new HashSet<>();

}

换句话说,商人可以拥有许多子商人。每个商人可以拥有零个,一个或多个服务。

@Entity
@Table(name = "SERVICES")
public class Service {

  @Id
  @GeneratedValue
  private long id;

  @ManyToOne
  @JoinColumn(name = "merchant_id")
  private Merchant merchant;

  // ...

}

以下查询将为我提供该商户ID的所有商户服务。

SELECT s FROM Service s WHERE s.merchantId = :merchantId ORDER BY s.name ASC

如果那个商人有招商,我如何在结果中包括每个招商的服务?

1 个答案:

答案 0 :(得分:1)

此HQL查询应返回您需要的结果:

SELECT s from Service s where s.id in 
(SELECT sm_s.id FROM Merchant m JOIN m.submerchants sm JOIN sm.services sm_s WHERE m.id = :merchantId) 
or s.id in 
(select ms.id from Merchant m2 JOIN m2.services ms WHERE m2.id = :merchantId)