There is a @ManyToMany table: User, user_role, roleuser.
The roleuser table contains roles: ROLE_USER, ROLE_ADMIN and others.
This is how I make the @ManyToMany tables relate to each other:
User.class
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
public List<Role> getRoleList() {
return roleList;
}
Role.class
@ManyToMany(mappedBy = "roleList", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
public List<User> getUserList() {
return userList;
}
public void addPerson(User user) {
userList.add( user );
user.getRoleList().add( this );
}
And this is how I add the user:
AddUser.class
User user = new User("Michael Joseph Jackson");
Role role = serviceJpa.findRoleByRole("ROLE_USER");
role.addPerson(user);
serviceJpa.saveRole(role);
The bottom line is that I don't want to use fetch = FetchType.EAGER. One role can have thousands of users, and I don't want to get all thousand users when I access the role. But to do this, I have to change FetchType.EAGER to FetchType.LAZY, but then in this case, a well-known error occurs when I add a user:
Message Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.test.shop.model.user.Role.userList, could not initialize proxy - no Session
I don’t know what to do about it. Please tell me what am I doing wrong?