CodexBloom - Programming Q&A Platform

Issue with Lazy Loading in Hibernate: Collection Not Initialized Exception

👀 Views: 220 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-03
Hibernate LazyLoading Spring Java

I need some guidance on This might be a silly question, but I'm facing a `org.hibernate.LazyInitializationException: could not initialize proxy - no Session` when trying to access my lazy-loaded collections after the Hibernate session is closed..... My entity setup involves a one-to-many relationship where a `Customer` can have many `Orders`. I've annotated the relationship in the `Customer` class as follows: ```java @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY) private List<Order> orders; // getters and setters } ``` And my `Order` class looks like this: ```java @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "customer_id") private Customer customer; // getters and setters } ``` In my service method, I retrieve a `Customer` by its ID and then try to access the `orders` collection immediately after the session is closed: ```java @Transactional public Customer getCustomerWithOrders(Long customerId) { Customer customer = customerRepository.findById(customerId).orElse(null); // The session is closed after this method ends return customer; } public void printCustomerOrders(Long customerId) { Customer customer = getCustomerWithOrders(customerId); if (customer != null) { System.out.println(customer.getOrders().size()); // This line throws the exception } } ``` I've tried changing the fetch type to `EAGER`, but that leads to performance issues due to fetching all orders even when they're not needed. I also considered using `@Transactional` on the method where I access the orders, but that complicates the design further. Is there a better way to handle this scenario without encountering the `LazyInitializationException`? I'm working on a service that needs to handle this. How would you solve this? My development environment is Ubuntu. Any help would be greatly appreciated! For context: I'm using Java on Windows 10.