Issue
I have a domain entity User, and because I needed to create 2 separate sets of stats for each user for competitive and non-competitive game, it has a OneToMany relation with UserStats and each User should contain 2 UserStat objects in a List userStats object.
However, when I call userRepo.findAllBy(SomeCondition) the returned List contains User objects but those User object don't contain the UserStat objects?
User Class:
@Entity(name = "User")
@Table(name = "user")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "username", unique = true)
private String username;
@Column(name = "password")
private String password;
private String name;
private String email;
private String location;
@JsonIgnore
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private List<UserStats> userStats;
}
USER STATS CLASS:
@Entity()
@Table(name = "userStats")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class UserStats {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userStatsId;
private Integer victories;
private Integer draws;
private Integer defeats;
private boolean isLeagueUserStats;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
}
UserService SignUp METHOD:
public void signUpUser(User user) {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
User savedUser = userRepository.save(user);
List<UserStats> userStatsList = new ArrayList<>();
UserStats userStats = new UserStats(0, 0, 0, false, savedUser);
UserStats leagueUserStats = new UserStats(0, 0, 0, true, savedUser);
userStatsRepository.save(userStats);
userStatsRepository.save(leagueUserStats);
userStatsList.add(userStats);
userStatsList.add(leagueUserStats);
user.setUserStats(userStatsList);
User savedUser2 = userRepository.save(user);
}
How can I make it so that when I save a User entity it also save's it's contained UserStats? How can I make it so when you retrieve User objects from the repository that they contain userStats list?
Thanks
Solution
It is probably because you need to add the cascade in order to let him save in cascade
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
and also, I am not sure if you are using a LAZY fetchType in purpose, but if at any point you have problems loading some data (I mean, if it is bringing to you just null data) it may be because of it, in that case you will have to use EAGER instead of LAZY
Answered By - Devck - DC
Answer Checked By - David Marino (JavaFixing Volunteer)