Hibernate 具有2多对1关系的Jpa
在使用hibernate jpa实现的spring引导应用程序中,我有以下3个表Hibernate 具有2多对1关系的Jpa,hibernate,jpa,spring-data-jpa,Hibernate,Jpa,Spring Data Jpa,在使用hibernate jpa实现的spring引导应用程序中,我有以下3个表 @Entity public class Event { @Id private Long eventId; @ManyToOne private Account account; ... } @Entity public class Account{ @Id private Long accountId; @ManyToOne pr
@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;
...
}
有改进的查询吗?试试这个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;
您需要将
@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
您在一个实体中拥有accountId和事件。为什么不简单地:
从帐户a中选择a.events,其中a.accountId=:accountId
,然后在java中复制事件?因为这将只返回指定帐户的事件。。。需要从与帐户ID关联的一方获取所有帐户不工作仅返回一个帐户而不是所有帐户的事件
select ce from Event ce
join fetch ce.account ba
join fetch ba.Party py
where ba.accountId=:accountId