Reputation: 341
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.
Upvotes: 1
Views: 729
Reputation: 40036
Whenever you see something like org.hibernate.LazyInitializationException: could not initialize proxy - no Session
, it is because of you are trying access a lazy-loading property outside transaction boundary.
In some case it is because you haven't setup transaction manager etc correctly, therefore once you get the entities from the repository, there is already no active Session.
In most case, you are trying to access lazy-loading property outside where you declared transactional. For example, there may be one Controller calling your Service (Your Service is where the transaction boundary is declared), and in the controller you are doing something like user.getImages()
. You should make sure you have already fetched the images before you return from Service. (There are some other ways like "Open Session In View" but that's never my preferred solution).
Such kind of lazy property access may not be explicit, for example, it may be triggered by you are calling toString()
of User
because of logging, or you are using a debugger to inspect the content of User
.
Off topic advise: Make sure you complies to Java's convention in naming. It should be UserImage
instead of User_images
Upvotes: 1