我有以下实体:
@Entity
public class ApplicationUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
private String username;
private String firstName;
private String lastName;
@Length(min = 2, max = 60)
private String password;
private Long tsRegistration;
private Long tslLastLogin;
private Long bonusCredit;
private String nationality;
private String battleTag;
private Integer mmr;
private boolean enabled;
private boolean tokenExpired;
private String nickname;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private List<Role> roles;
和
@Entity
@Data
public class Match {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany
public List<ApplicationUser> users;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "tournament_id")
public Tournament tournament;
public Integer qualifyingRound;
public String winner;
public Match(List<ApplicationUser> users, Tournament tournament, Integer qualifyingRound) {
this.users = users;
this.tournament = tournament;
this.qualifyingRound = qualifyingRound;
this.winner = null;
}
我正在开发一种测试,试图在给定的锦标赛中为玩家生成新的比赛。比赛开始时,已经为用户生成了比赛,并且比赛例外。但是,当我与相同的用户,相同的锦标赛,但排位赛不同而产生比赛时,(因为相同的用户可能恰好必须在同一锦标赛中进行对战),我得到了
Unique index or primary key violation: "UK_9PXJMR2KVN9AQYI2A0AYB5BSC_INDEX_2 ON PUBLIC.MATCH_USERS(USERS_ID) VALUES (2, 1)"; SQL statement:
insert into match_users (match_id, users_id) values (?, ?) [23505-197]
执行以下查询后:
Hibernate:
insert
into
match_users
(match_id, users_id)
values
(?, ?)
为什么会这样? match_id是否应该与之前插入的ID不同?这是生成错误的测试代码:
@Test
public void prova(){
SwissSystemTournament tournament = (SwissSystemTournament) tournamentService.getRepository().save(new SwissSystemTournament("Test tournament", 12,
"Hearthstone", "image/img2.jpg", "Italy", "3v3", System.currentTimeMillis(), 3));
List<ApplicationUser> users = new ArrayList<>();
users.add(new ApplicationUser("testuser000@gmail.com", "AliceF", "AliceL", "sdadasdaddsada",
"Europe", "TestUser000", roleRepository.findByName("ROLE_USER"), "TestNicktestuser000"));
users.add(new ApplicationUser("testuser001@gmail.com", "BobF", "BobL", "wqeqweqweeq",
"Europe", "TestUser001", roleRepository.findByName("ROLE_USER"), "TestNicktestuser001"));
tournamentService.getRepository().save(tournament);
userService.getRepository().save(users.get(0));
userService.getRepository().save(users.get(1));
Match match1 =new Match(users,tournament,1);
matchService.getRepository().save(match1).getId();
Match match2 = new Match(users,tournament,2);
matchService.getRepository().save(match2).getId();
}
答案 0 :(得分:0)
正如rj-hwang所说,我必须对Match.users使用@manyToMany批注,因为这是用户和match之间的正确关系。谢谢!