为什么 Hibernate 在使用 @Fetch 时执行多个 SELECT 查询而不是一个查询(FetchMode.JOIN)
我有以下查询,我希望在单个选择请求中运行:
@NamedQuery(name=Game.GET_GAME_BY_ID1,
query = "SELECT g FROM Game g " +
"JOIN FETCH g.team1 t1 " +
"JOIN FETCH t1.players p1 " +
"JOIN FETCH p1.playerSkill skill1 " +
"where g.id=:id")
问题在于所有内容都是由单独的多个查询获取的。我希望在单个请求中仅获取团队和团队的玩家以及每个玩家的技能。但相反,我有多个选择查询来获取每个团队,球员,每个球员的统计数据和技能。
以下是与给定的注释一起使用的实体:
游戏实体:
public class Game implements Serializable {
private Integer id;
private Integer dayNumber;
private Long date;
private Integer score1;
private Integer score2;
private Team team1;
private Team team2;
....
@ManyToOne(fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="team_id1")
public Team getTeam1() {
return team1;
}
public void setTeam1(Team team1) {
this.team1 = team1;
}
// uni directional many to one association to Team
@ManyToOne(fetch=FetchType.EAGER)
@Fetch(FetchMode.JOIN)
@JoinColumn(name="team_id2")
public Team getTeam2() {
return team2;
}
public void setTeam2(Team team2) {
this.team2 = team2;
}
}
团队实体:
public class Team implements Serializable {
...
private Set<Player> players;
...
@OneToMany(mappedBy="team", targetEntity=Player.class, fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@Fetch(FetchMode.JOIN)
@OrderBy(value="batOrder, pitRotationNumber ASC")
public Set<Player> getPlayers() {
return players;
}
public void setPlayers(Set<Player> players) {
this.players = players;
}
}
玩家实体:
public class Player implements Serializable {
private PlayerStat playerStats;
private PlayerSkill playerSkill;
...
@OneToOne(mappedBy="player", cascade=CascadeType.ALL)
@Fetch(FetchMode.JOIN)
public PlayerStat getPlayerStats() {
return this.playerStats;
}
public void setPlayerStats(PlayerStat playerStats) {
this.PlayerStats = playerStats;
}
...
@OneToOne(mappedBy="player", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@Fetch(FetchMode.JOIN)
public PlayerSkill getPlayerSkill() {
return this.playerSkill;
}
public void setPlayerSkill(PlayerSkill playerSkill) {
this.playerSkill = playerSkill;
}
}
你能指出所犯的错误吗?我需要一个选择查询来加载游戏,它是团队,团队的球员和每个球员的技能。
编辑1:这里是postgresql日志(其中的一部分),纯sql查询:http://pastebin.com/Fbsvmep6
为简单起见,在此问题中更改了表格的原始名称,Game是GamelistLeague,Team是TeamInfo,并且有BattterStats和PitcherStats而不是一个PlayerStats。
日志中的第一个查询是上面这个问题(命名查询)中所示的查询,如果我直接在数据库中执行它,则会根据需要返回所有内容。