如何强制 Hibernate JPA 创建连接查询
How to force Hibernate JPA to create a join query
我目前正在使用 Spring Data JPA 和 Hibernate 开发 spring 启动应用程序。我当前的设置如下:
我的 TeamMapping 存储库:
public interface TeamMembershipMapping Repository extends JpaRepository<TeamMembershipMapping, Integer>
{
public List<TeamMembershipMapping> getByMemberId(Integer memberId, Pageable pageable);
}
我的 TeamMembershipMapping 实体:
@Entity
@Table(name = "teamMembership")
public class TeamMembershipMapping
{
@Id
private Integer teamMembershipId;
@Column(table = "teamMembership", name = "memberId")
private Integer memberId;
@Enumerated
@Column
private TeamMembershipStatus status;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "teamId")
private Team team;
---Getters and Setters---
}
我的团队实体:
@Entity
@Table(name = "team")
@SecondaryTable(name = "summaryTeam")
public class Team
{
@Id
private Integer teamId;
@Column
private String name;
@Column
private String description;
@Column(table = "summaryTeam")
private Integer wins;
@Column(table = "summaryTeam", nullable = true)
private Integer losses;
--Getters and Setters---
}
现在我的问题是,当我调用 getByMemberId 来检索特定成员拥有的所有 TeamMembershipMappings 时,Hibernate 正在生成一个 sql select 来获取所有 TeamMappings,然后执行 sql select 为每个映射获取团队信息。因此,如果该成员是 4 个团队的一员,那就是 1+4 sql select 可以在一次加入中完成。
那么我如何强制 Hibernate 在一个大连接中收集所有信息 select?
在实体 TeamMembershipMapping
中,您可以像这样创建一个命名查询:
select tmm.team from TeamMembershipMapping tmm where tmm.memberId = :memberId;
这只是一个简单的查询。
我目前正在使用 Spring Data JPA 和 Hibernate 开发 spring 启动应用程序。我当前的设置如下:
我的 TeamMapping 存储库:
public interface TeamMembershipMapping Repository extends JpaRepository<TeamMembershipMapping, Integer>
{
public List<TeamMembershipMapping> getByMemberId(Integer memberId, Pageable pageable);
}
我的 TeamMembershipMapping 实体:
@Entity
@Table(name = "teamMembership")
public class TeamMembershipMapping
{
@Id
private Integer teamMembershipId;
@Column(table = "teamMembership", name = "memberId")
private Integer memberId;
@Enumerated
@Column
private TeamMembershipStatus status;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "teamId")
private Team team;
---Getters and Setters---
}
我的团队实体:
@Entity
@Table(name = "team")
@SecondaryTable(name = "summaryTeam")
public class Team
{
@Id
private Integer teamId;
@Column
private String name;
@Column
private String description;
@Column(table = "summaryTeam")
private Integer wins;
@Column(table = "summaryTeam", nullable = true)
private Integer losses;
--Getters and Setters---
}
现在我的问题是,当我调用 getByMemberId 来检索特定成员拥有的所有 TeamMembershipMappings 时,Hibernate 正在生成一个 sql select 来获取所有 TeamMappings,然后执行 sql select 为每个映射获取团队信息。因此,如果该成员是 4 个团队的一员,那就是 1+4 sql select 可以在一次加入中完成。
那么我如何强制 Hibernate 在一个大连接中收集所有信息 select?
在实体 TeamMembershipMapping
中,您可以像这样创建一个命名查询:
select tmm.team from TeamMembershipMapping tmm where tmm.memberId = :memberId;
这只是一个简单的查询。