【问题标题】:Spring data JPA many to many retrieveSpring数据JPA多对多检索
【发布时间】:2017-09-27 14:37:42
【问题描述】:

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

}

【问题讨论】:

  • 你已经尝试了什么?可以通过 jpa
  • 为什么有 ABMapping 实体?它是无用的(并且有问题,因为映射到与用于多对多关联的连接表相同的表)。那就是说:你试过了吗?你读过 JPQL 的文档吗?
  • @MaciejKowalski 我在 AEntityRepository 中尝试了类似的方法,它扩展了 CrudRepository 以获取 Bentities,但不确定如何从 Bentity 获取 CEntity。 List findBEntitiesByAEntityId(long Id);
  • 除了像 findByName 这样的琐碎查询之外,您应该使用有意义的方法名称,使用 Query 注释对方法进行注释,并指定您的 JPQL 查询。
  • @JBNizet 好的。我已经浏览了 jpql 示例和文档,并提出了以下查询。你能检查一下我在这里缺少什么吗? select distinct c from CEntity c join c.BEntity b join b.AEntity a where a.id = :id

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


【解决方案1】:

我接受了@JB Nizet 的建议。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-10
    • 2021-02-26
    • 2022-01-02
    • 2017-11-18
    • 2017-02-01
    • 2013-03-29
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多