2016-05-16 75 views
0

我需要解決這個問題:@OneToMany和@ManyToOne

@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; 
} 

如果我有一個像場也Team team;將通過mappedBy = team;容易。

我可以使用列隊,而不是兩個字段,並添加@ManyToMany註釋,但它不是很好的解決方案恕我直言。

+0

([指向在JPA /休眠相同實體的多個@ManyToOne字段]的可能的複製http://stackoverflow.com/questions/21345203/multiple-manytoone-fields-pointing-to-same-entity- in-jpa-hibernate) –

+0

我看到了,但它並不令人興奮,這同樣的問題。 列表 matchesAsTeamA; + 列表 matchesAsTeamB; 而不是 列表匹配; 是不合邏輯的.. – Bambelal

回答

0

這裏你的問題是,你需要記住,一些比賽是「在家」,一些比賽是「離開」。像homeTeamawayTeam這樣的想法將比teamAteamB更容易。

每支球隊將有一套OneToMany主場比賽套路和另外一套OneToMany爲客場比賽設置。然後,如果需要,您可以添加一個便捷方法來獲得所有匹配。

@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; 
} 
0

假設您的匹配表具有Team表的team_id(外鍵)主鍵。此代碼可能會幫助你。 tam有很多比賽,許多球隊都與一場比賽有關。

在你的團隊的實體:

@OneToMany(mappedBy = "team", cascade = CascadeType.ALL) 
List<Match> matches= [] 

在您的匹配實體:

@ManyToOne 
@JoinColumn(name = "TEAM_ID") 
Team team 
0

這是很多比賽可以關聯到一個團隊一個事實,很多球隊(正好2)可以與比賽相關聯。

既然你想要一個包含團隊所有匹配的列表,而不需要將團隊分成兩個映射(對於A或B),我建議你在它們之間使用@ManyToMany關係映射。