简体   繁体   中英

CascadeType.PERSIST does not save properly

I assume that I made a mistake somewhere:
There are 2 entities (removed all useless fields):

1. Player (many players -> in 1 team)

@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. Team (one team contains many players)

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

Edited (Test examples):
1. In this case I will get an empty "team_id" and empty array from the fetching:

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. The same + setTeam() method before saving:

...
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'}]}]

I'm using spring-boot latest (2.1.2.RELEASE) and H2 (1.4.197).
My issue is when I am saving:
1. If I try to save a Player with a Team - it's fine. Field team_id will be filled and then when I fetch it finds a team related to this player.
2. If I try to save a Team with some new Players - it is being saved, but Players will have null in the team_id field inside db. If I try to fetch - I will get an empty array.
3. If I remove mappedBy from the Team I will get new TEAM_PLAYERS table and fetching will work correct (I thinkg it's wrong; team_id will stay null ).

What did I miss?

You have your Team mapped to "team_id" in your Player class, but your @Id property is "id". change it from:

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

To:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM