Hibernate throws LazyInitializationException when accessing @OneToMany collection after transaction commits
This might be a silly question, but I can't seem to get I'm working on a project and hit a roadblock... I'm working with a `LazyInitializationException` when trying to access a `@OneToMany` collection in my Hibernate application after the session has been closed. My setup uses Spring Data JPA with Hibernate 5.4.30.Final, and I've configured my entities with JPA annotations. Here's the relevant part of my code: ```java @Entity public class Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "author", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Book> books = new ArrayList<>(); // Getters and setters } @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @ManyToOne @JoinColumn(name = "author_id") private Author author; // Getters and setters } ``` In my service layer, I fetch an `Author` by its ID and then try to access the `books` collection: ```java public Author findAuthorWithBooks(Long authorId) { Author author = authorRepository.findById(authorId).orElseThrow(() -> new RuntimeException("Author not found")); // Transaction commits here return author; } ``` However, when I call `findAuthorWithBooks` and then try to access `author.getBooks()` in a separate method, I get the following behavior: ``` org.hibernate.LazyInitializationException: could not initialize proxy - no Session ``` I've tried changing the `fetch` type to `FetchType.EAGER`, but that leads to performance optimization due to loading unnecessary data. I've also considered using `@Transactional` on my service method, but that doesn't seem to solve the scenario since I'm trying to access the books collection after the transaction has completed. What is the best way to handle lazy-loaded collections in this scenario without running into `LazyInitializationException`? Should I retrieve the books in the same method or is there a more elegant solution? Has anyone else encountered this? This is my first time working with Java 3.11. Thanks, I really appreciate it!