getting org.hibernate.LazyInitializationException: could not initialize proxy - no Session when I call findByUserEmail(String email)
The service class (where I'm calling this function) is marked as @Transactional
Repository
@Repository
public interface UserImagesRepository extends CrudRepository<User_images, Integer> {
List<User_images> findByUserEmail(String email);
}
User
@Entity
@Table(name = "users")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String email;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<User_images> images = new HashSet<User_images>(0);
//getters and setters
}
User_images
@Entity
@Table(name = "user_images")
public class User_images implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId")
private User user;
// getters and setters
}
___UPDATE___
The UserImageRepository
has no implementation, queries are automatically generated from method name directly. docs
I don't want to use eager loading as its bad practice.
findByUserEmail(String email)
,if in this fuction you are fetching some thing which is associated with another table after the service method call it will give the LazyInitailzation exception as session is closed.try replacing with fetch=FetchType.Eager all places , it should work. 1.javarevisited.blogspot.in/2014/04/… 2.uaihebert.com/four-solutions-to-the-lazyinitializationexception – Amar AgrawalfindByUserEmail
method? Perhaps your stacktrace would help us, or even the actual code in this method. – DuncanKinnear