[英]@OneToMany and @ManyToOne
I need to resolve this problem: 我需要解决这个问题:
@Entity
public class Team
{
@OneToMany // how mapped it ?
private List<Match> matches; // all played and coming matches
}
@Entity
public class Match
{
@ManyToOne
@Column( nullable = false )
private Team teamA;
@ManyToOne
@Column( nullable = false )
private Team teamB;
}
If I had one field like Team team;
如果我有像
Team team;
这样的领域Team team;
it would be easier by using mappedBy = team;
使用
mappedBy = team;
会更容易mappedBy = team;
. 。
I could use List teams instead of two fields and add @ManyToMany annotation, but it isn't good solution imho. 我可以使用列表团队而不是两个字段并添加@ManyToMany注释,但这不是一个好的解决方案。
Assuming that your Match table has a team_id (foreign key) primary key of the Team table. 假设您的Match表具有Team表的team_id(外键)主键。 This code might help you.
此代码可能会对您有所帮助。 A tam has many matches and many teams are associated to one match.
一个tam有很多比赛,并且许多团队与一个比赛相关联。
In your Team entity : 在您的团队实体中:
@OneToMany(mappedBy = "team", cascade = CascadeType.ALL)
List<Match> matches= []
In your Match entity : 在您的Match实体中:
@ManyToOne
@JoinColumn(name = "TEAM_ID")
Team team
It is a fact that many matches can be associated to one team, and many teams (exactly 2) can be associated to a match. 一个事实是,许多比赛可以与一个团队相关联,而许多团队(恰好2个)可以与一场比赛相关联。
Since you want one list with all matches the team is associated to without splitting into two mappings in team (for A or B) I would suggest that you use a @ManyToMany relation mapping between them. 由于您希望一个与所有比赛都匹配的列表,而又不拆分到团队中的两个映射(对于A或B),因此建议您在它们之间使用@ManyToMany关系映射。
Your problem here is that you need to keep in mind that some matches are "at home" and some matches are "away". 您在这里的问题是,您需要记住一些比赛是“在家”而有些比赛是“离开”。 Thinking of it like that
homeTeam
and awayTeam
will be easier than teamA
and teamB
. 像
homeTeam
和awayTeam
这样的homeTeam
比teamA
和teamB
容易。
Each team will have a OneToMany
set of home matches and another OneToMany
set for away matches. 每个团队将有一个
OneToMany
的主场比赛和另一个OneToMany
的客场比赛。 Then, you can add a convenience method to get all matches if want. 然后,如果需要,您可以添加一种便捷方法来获取所有匹配项。
@Entity
public class Team {
@OneToMany(mappedBy="homeTeam")
private Set<Match> homeMatches = new HashSet<>();
@OneToMany(mappedBy="awayTeam")
private Set<Match> awayMatches = new HashSet<>();
// getters and setters
// special getter if you want it
public Set<Match> getAllMatches() {
Set<Match> allMatches = new HashSet<>();
allMatches.addAll(homeMatches);
allMatches.addAll(awayMatches);
return allMatches;
}
}
@Entity
public class Match {
@ManyToOne
@JoinColumn(name = "HOME_TEAM_ID", referencedColumnName = "TEAM_ID")
private Team homeTeam;
@ManyToOne
@JoinColumn(name = "AWAY_TEAM_ID", referencedColumnName = "TEAM_ID")
private Team awayTeam;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.