繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM