我正在建立一个休闲羽毛球运动的门户网站(注册和分析游戏统计数据)。昨天,当我开始实施一个显示球队统计数据的视图(例如,比赛/赢/输游戏......)时,我发现了一个神秘的虫子。
当我用查询检索所有球队时,应该包含远离家乡的比赛系列的球场也包括在主场比赛中进行的系列赛。包含在主场进行的系列赛的场地确实不包含远离家乡的系列赛(这是我想要的行为)。
此外,如果我再次执行查询(更新页面),则包含从家中播放的游戏系列的字段开始增长。每次执行查询时,主游戏集都会在awaySeries字段中再次注册。
例如:
第一次查询:
Team1
gameSeriesAway:Team1 vs Team2, Team1 vs Team3
gameSeriesHome:Team1 vs Team3
第二次查询:
Team1
gameSeriesAway:Team1 vs Team2, Team1 vs Team3 , Team1 vs Team3
gameSeriesHome:Team1 vs Team3
Team.java
@Entity
@NamedQueries({@NamedQuery(name = "Team.findAll", query="SELECT distinct t FROM Team t")})
public class Team implements Comparable<Team> {
public static final String FIND_ALL_TEAMS = "Team.findAll";
//Fields
@Id
private String name;
private String description;
//Relationships
@OneToMany(mappedBy = "team")
private List<Player> players;
@ManyToMany
private List<Division> divisionHistory;
@OneToMany(mappedBy="homeTeam")
private List<GameSeries> homeSeries;
@OneToMany(mappedBy="awayTeam")
private List<GameSeries> awaySeries;
...
...
@Override
public boolean equals(Object obj) {
if(obj instanceof Team)
return name.equals(((Team) obj).name)? true:false;
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
GameSeries.java
@Entity
public class GameSeries {
public static final int NUMBER_OF_GAMES = 5;
// Fields
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private Timestamp playDate;
// Relationships
@OneToMany(mappedBy = "series")
private List<Game> games;
@ManyToOne
private Division division;
@ManyToOne
private Team homeTeam;
@ManyToOne
private Team awayTeam;
@Override
public boolean equals(Object obj) {
if (obj instanceof GameSeries)
return playDate.equals(((GameSeries) obj).playDate)
&& homeTeam.equals(((GameSeries) obj).homeTeam)
&& awayTeam.equals(((GameSeries) obj).awayTeam)
? true : false;
return false;
}
@Override
public int hashCode() {
return playDate.hashCode() + 2*homeTeam.hashCode() + awayTeam.hashCode();
}
}
相应的表格如下所示:
GameSeries
id PRIM
playDate
awayTeam_name MUL
division_id MUL
homeTeam_name MUL
团队
名称PRIM
描述
我有一种预感,这是一个非常简单的问题需要解决,但由于我是JPA / EJB的新手,我无法想出这个问题
答案 0 :(得分:0)
逐行调试代码后,似乎发现了错误。
在我的统计工具类中,我将awayGameSeries和homeGameSeries加入了一个List:
List<GameSeries> allSeries = new ArrayList<GameSeries>(team.getAwaySeries());
allSeries.addAll(team.getHomeSeries());
... compute statistics for all game series
new ArrayList(argument)“指向”原始的awayGameSeries,并且将对象添加到新列表因此也会附加awayGameSeries。 (即,当执行 addAll(team.getHomeSeries()); 行时,将homeGameSeries添加到awayGameSeries中)
要解决此问题,只需添加一行代码:
List<GameSeries> allSeries = new ArrayList<GameSeries>();
allSeries.addAll(team.getAwayGameSeries());
allSeries.addAll(team.getHomeSeries());