Spring数据JPA可以多次检索

时间:2017-09-27 14:37:42

标签: java hibernate jpa spring-data-jpa jpql

我有如下实体。我需要使用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;
    }
}

实体ABMapping

@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;
}

}

1 个答案:

答案 0 :(得分:1)

我选择了@JB Nizet的建议。

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