JPA与2多对一关系

时间:2020-01-14 12:40:00

标签: hibernate jpa spring-data-jpa

在具有hibernate 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) ) 

任何改进的查询?

2 个答案:

答案 0 :(得分:0)

如果有任何问题,请尝试使用此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;

答案 1 :(得分:0)

您需要在@JoinColumn(name={{joinKeyName}})批注中添加@ManyToOne

示例:

    @ManyToOne
    @JoinColumn(name="accountId")
    private Account account;

然后,您的HQL查询如下:

select ce from Event ce 
   join fetch ce.account ba 
   join fetch ba.Party py 
   where ba.accountId=:accountId