首页 > 解决方案 > 具有2个多对一关系的Jpa

问题描述

在具有休眠 jpa 实现的 Spring Boot 应用程序中,我有 3 个表。

@Entity
public class Event {

    @Id
    private Long eventId;

    @ManyToOne
    private Account account;
    ...
}

@Entity
public class Account{

    @Id
    private Long accountId;

    @ManyToOne
    private Party party;

    @OneToMany(mappedBy = "account")
    private List<Event> events;
    ...
}

@Entity
public class Party{
    @Id
    private Long partyId;

    @OneToMany(mappedBy = "party")
    private List<Account>accounts;
    ...
}

我有一个 accountId,我想从中获取与该帐户相关的所有事件。是否可以在一个查询中完成?

其实我已经做到了

select ce from Event ce where ce.account in 
 ( select ba from Account ba join ba.party p where p.partyId in 
    ( select  py from Party py join py.accounts bao where bao.accountId=:accountId) ) 

任何改进的查询?

标签: hibernatejpaspring-data-jpa

解决方案


试试这个 sql,如果有任何问题通知我

  select * from Event as e 
inner join Account as acc on e.account_accountId = acc.accountId 
inner join Party as p on acc.party_partyId =p.partyId
where acc.accountId=:accountId;

推荐阅读