Spring 数据 JPA 多对多检索

Spring data JPA many to many retrieve

我有如下实体。我需要使用 AEntity 的 ID 从 CEntity 检索 CID 列表;

我必须遍历 AEntity -> ABMapping -> BEntity -> 从 CEntity 获取 CID。

有没有办法在 JPA 中实现此目的,或者我是否应该采用本机查询方式连接所有四个表并从 CEntity 获取 CID?

实体 A

@Entity
public class AEntity {

@Id
private long id;

@ManyToMany
@JoinTable(name = "ABMapping", joinColumns = @JoinColumn(name = "AEntity_ref", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "BEntity_ref", referencedColumnName = "id"))
private List<BEntity> bEntities = new ArrayList<>();

}

实体 B

@Entity
public class BEntity {

@Id
private long id;

private CEntity cEntity;

@ManyToMany(mappedBy = "bEntities")
private List<AEntity> aEntities;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "cEntityId")
public CEntity getCEntity() {
    return cEntity;
    }
}

实体AB映射

@Entity
public class ABMapping {

@Id
private long id;

@Column(name="AEntity_ref")
private long ARefId;

@Column(name = "BEntity_ref")
private long BRefId;

}

实体 C

@Entity
public class CEntity {

@Id
private long id;

private String CID;

private List<BEntity> bEntity;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "c", cascade = 
CascadeType.ALL)
public List<BEntity> getBEntities() {
   return bEntity;
}

@Column(name = "CID_column")
public String getCId() {
   return CID;
}

public void setCId(String CID) {
    this.CID = CID;
}

}

我接受了@JB Nizet 的建议。

select distinct c from AEntity a join a.bEntities b join b.cEntity c where a.id = :id