1

I'm trying to use Inheritance using this project https://github.com/Baeldung/spring-security-registration.

This is my User:

@Data
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "TYPE")
public abstract class User {
     @ManyToMany(fetch = FetchType.EAGER)
     @JoinTable(name = "users_roles",joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"))
     private Collection<Role> roles;
}

and some subclass like UserAdmin:

@Entity
@DiscriminatorValue("ADMIN")
public class UserAdmin extends User {}

Then my role class is like this:

@Data
@Entity
public class Role {
     @ManyToMany(mappedBy = "roles")
     private Collection<User> users;
}

But I got this error when I register a user:

o.h.LazyInitializationException: failed to lazily initialize a collection of role: com.baeldung.persistence.model.Role.users, could not initialize proxy - no Session

Need help guys.

1
  • when you do many-to-many relations, they has to evaluate lazily since you cannot add 2 cycling data at the same time. check your code to see where you miss this requirements Commented Jan 17, 2022 at 10:42

1 Answer 1

1

We need a bit more context, but you generally have two options:

  1. Have the method where you call "getRoles()" be annotated with @Transactional.

or

  1. Create a method in jpa with a @Query("SELECT u from user u join fetch u.roles where u.id =:id").
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your reply. I've just download the project and introduced UserAdmin and UserStaff. Got error when calling RegistrationController#confirmRegistration
I have add annotation to RegistrationController#authWithoutPassword but still got error
I just noticed that the project is a bit more complex, I think it should still work if you were to add @Transactional on RegistrationController#confirmRegistration. But that is kinda a bad practice
indeed, not a good practice adding this annotation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.