CodexBloom - Programming Q&A Platform

How to handle LazyInitializationException when using `@Transactional` in Spring with Hibernate?

๐Ÿ‘€ Views: 1504 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-14
hibernate spring lazy-loading java

I've been banging my head against this for hours. I'm working with a `LazyInitializationException` when trying to access a lazily-loaded collection outside of a transactional context in my Spring application using Hibernate 5.4. I have a `User` entity that has a `@OneToMany` relationship with an `Order` entity. The `@Transactional` annotation is on my service method to retrieve the user, but it seems like the orders are not being fetched when I access them after the transaction has completed. Hereโ€™s the relevant part of my entity classes: ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "user", fetch = FetchType.LAZY) private Set<Order> orders; } @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "user_id") private User user; } ``` And hereโ€™s my service method: ```java @Service public class UserService { @Autowired private UserRepository userRepository; @Transactional public User getUser(Long userId) { return userRepository.findById(userId).orElseThrow(() -> new EntityNotFoundException("User not found")); } } ``` When I try to access `user.getOrders()` after the service method completes, I get: ``` org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.User.orders, could not initialize proxy - no Session ``` Iโ€™ve tried changing the fetch type to `FetchType.EAGER`, but that leads to performance optimization due to excessive data being loaded. I also considered using `@Transactional(readOnly = true)` on my method, but the scenario continues. Is there a best practice or configuration that can guide to handle this situation without compromising performance? I appreciate any guidance on how to properly manage the lifecycle of these entities. Thanks! Has anyone else encountered this?