CascadeType.PERSIST无法正确保存

时间:2019-01-26 20:17:14

标签: java hibernate spring-boot spring-data-jpa

我认为我在某个地方犯了一个错误:
有2个实体(删除了所有无用的字段):

1。玩家(许多玩家->在1个团队中)

@Component
@Entity
@Table(name = "player")
public class Player extends BaseEntity implements Serializable {

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@Min(0)
@Column(name = "uid")
private Integer uid;

@ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinColumn(name = "team_id", referencedColumnName = "team_id")
private Team team;

2。团队(一个团队包含许多玩家)

@Component
@Entity
@Table(name = "team")
public class Team extends BaseEntity implements Serializable {

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@Min(0)
@Column(name = "team_id", unique = true)
private Integer teamId;

@OneToMany(mappedBy = "team", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private Set<Player> players;

已编辑(测试示例):
1.在这种情况下,我将从获取中得到一个空的“ team_id”和一个空数组:

Team team = new Team(100, "Red");
Player p1 = new Player(4, "Aaa");
Player p2 = new Player(5, "Bbb");
team.addPlayer(p1);
team.addPlayer(p2);
store.getTeamStore().save(team);
System.out.println(store.getTeamStore().findAll());
-> [Team{id=1, teamId=100, teamAbbrev='Red', players=[]}]

2。保存前使用相同的+ setTeam()方法:

...
p1.setTeam(team)
p2.setTeam(team)
store.getTeamStore().save(team);
System.out.println(store.getTeamStore().findAll());
-> [Team{id=1, teamId=100, teamAbbrev='Red', players=[Player{id=2, uid=4, name='Aaa'}, Player{id=3, uid=5, name='Bbb'}]}]

我正在使用spring-boot Latest(2.1.2.RELEASE)和H2(1.4.197)。
我的问题是保存时:
1.如果我尝试用Player保存一个Team-很好。字段team_id将被填充,然后在我获取时会找到与该玩家相关的团队。
2.如果我尝试用新的Team保存一个Players-它正在保存,但是Players在db内部的null字段中将有team_id 。如果我尝试获取-我将得到一个空数组。
3.如果从mappedBy中删除Team,我将得到新的TEAM_PLAYERS表,并且提取将正常工作(我认为这是错误的; team_id将保持null )。

我想念什么?

1 个答案:

答案 0 :(得分:0)

您已将您的团队映射到Player类中的“ team_id”,但您的@Id属性是“ id”。更改为:

94707C897D899C5A8rt1.c.ie.o9D209@Bp60551s9lEf4vC91c4m

收件人:

@JoinColumn(name = "team_id", referencedColumnName = "team_id")
private Team team;