В моем проекте Spring есть две сущности: ApplicationUser и Tournament
@Entity
public class ApplicationUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
private String username;
private String firstName;
private String lastName;
@JsonIgnore
@Length(min = 2, max = 60)
private String password;
private Long tsRegistration;
private Long tslLastLogin;
private Long bonusCredit;
private String nationality;
private String battleTag;
private String mmr;
private boolean enabled;
private boolean tokenExpired;
@JsonIgnore
@OneToMany(mappedBy = "applicationUser")
private List<ConfirmationUri> confirmationUri;
@JsonIgnore
@ManyToMany
@JoinTable(name = "user_matches",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "matches_id", referencedColumnName = "id"))
private List<Matches> matches;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
}
@Entity
public class Tournament {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public long id;
public String name;
public Integer maxPlayers;
public String game;
@ElementCollection
@CollectionTable(name="listOfUsers")
public List<Long> ids;
@OneToMany(mappedBy = "tournament")
public List<Matches> matches;
public String imagePath;
public Long timestamp;
public TournamentState tournamentState;
public String region;
public String type;
}
Я реализовал контроллер REST, который позволяет пользователю зарегистрироваться на данный турнир
@RequestMapping(method = POST, path = "/tournaments/{id}")
@ResponseBody
public ResponseEntity<?> registerInTournament(@PathVariable long id) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<ApplicationUser> userList = applicationUserRepository.findByUsername(auth.getName());
if (userList.isEmpty())
return ResponseRestBuilder.createErrorResponse("User with email " + auth.getName() + " not found");
ApplicationUser user = userList.get(0);
List<Tournament> tournamentList = tournamentRepository.findById(id);
if (tournamentList.isEmpty())
return ResponseRestBuilder.createErrorResponse("Tournament id " + id+ " not found");
Tournament tournament = tournamentList.get(0);
ApplicationUser user1 = userList.get(0);
if (tournament.getUsers().contains(user))
return ResponseRestBuilder.createErrorResponse("User id " + user.id + " is already registered in tournament" +
"with id " + id);
if(tournament.getUsers().size() >= tournament.maxPlayers)
return ResponseRestBuilder.createErrorResponse("Tournament has reached max capacity");
tournament.addUsers(user1);
tournamentRepository.save(tournament);
user1.tournament.add(tournament);
applicationUserRepository.save(user1);
return ResponseRestBuilder.createSuccessResponse("user successfully registered to tournament");
}
.чтобы иметь возможность хранить информацию о том, что пользователь зарегистрирован в турнире, мне нужно не только выполнить сохранение турнира
tournament.addUsers(user1);
tournamentRepository.save(tournament);
, но и сохранить приложение пользователя
user1.tournament.add(tournament);
applicationUserRepository.save(user1);
Isэто правильное поведение?Есть ли способ просто сохранить один репозиторий и отразить изменения в других?