LazyInitializationException when using @Inheritance

Viewed 47

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 Answers

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").
Related