Search code examples
javahibernatejpaspring-data-jpajpql

Spring data JPA many to many retrieve


I have entities as below. I need to retrieve list of CIDs from CEntity using AEntity's id;

I have to traverse thru AEntity -> ABMapping -> BEntity -> fetch CID from CEntity.

Is there a way to achieve this in JPA or Should I go native query way joining all four tables and get CIDs from CEntity?

Entity 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<>();

}

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

Entity ABMapping

@Entity
public class ABMapping {

@Id
private long id;

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

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

}

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

}

Solution

  • I went with what @JB Nizet has suggested with.

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