gpt4 book ai didi

java - jpa中多对多关系中间表中的附加列

转载 作者:行者123 更新时间:2023-11-29 05:15:46 28 4
gpt4 key购买 nike

我有两个类 Game 和 Team,它们之间存在多对多关系。

游戏:

@Entity
@Table(name = "GAME")
public class Game extends Model {

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="GAME_TEAM",
joinColumns={@JoinColumn(name="GAME_ID")},
inverseJoinColumns={@JoinColumn(name="TEAM_ID")})
private List<Team> teams = new ArrayList<Team>();

public List<Team> getTeams() {
return teams;
}

public void setTeams(List<Team> teams) {
this.teams = teams;
}
}

团队:

@Entity
@Table(name = "TEAM")

public class Team extends Model {


@Column(name = "TEAM_NAME")
private String teamName;

@OneToMany(mappedBy = "team", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Player> player = new LinkedHashSet<Player>();

@ManyToMany(cascade=CascadeType.ALL, mappedBy="teams")
private Set<Game> games;

public Set<Player> getPlayer() {
return player;
}

public void setPlayer(Set<Player> player) {
this.player = player;
}

public Set<Game> getGames()
{
return games;
}

public void setGames(Set<Game> games) {
this.games = games;
}

public String getTeamName() {
return teamName;
}

public void setTeamName(String teamName) {
this.teamName = teamName;
}

在这两个类 GAME_TEAM 之间有第三个中间表,它具有 team_id、game_id,它们是游戏和团队类 ID 的外键。因此,每当我更新团队和游戏时,我都会自动更新 game_team。

好的。好的。现在的问题是什么?我有第三列 WON_BY 也必须更新。如果没有这个额外的第三列,我就不必创建第三类 GameTeam。

要更新不是外键的第三列,我应该为中间表创建一个实体类吗?如果是这样,我应该使用哪种方法或注释?

最佳答案

You need to have a separate entity class to persist your 'WON_BY', and you need to re-factor your existing entity classes a bit, since the solution is quite big refer the below sample example, which will definitely solves your problem.

http://www.codejava.net/frameworks/hibernate/hibernate-many-to-many-association-with-extra-columns-in-join-table-example

关于java - jpa中多对多关系中间表中的附加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049038/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com