Java 11: Performance implementing Hibernate FetchType.LAZY and Multiple Detached Entities
I'm following best practices but Quick question that's been bugging me - I'm experiencing performance optimization when retrieving entities using Hibernate with `FetchType.LAZY`. I have a parent entity that has a collection of child entities, and I noticed that when I load the parent, the associated children are not being fetched until I access them. This is expected behavior, but I have a scenario where I detach the parent entity and then try to access the children, leading to a `LazyInitializationException`. Here's the relevant part of my code: ```java @Entity public class Parent { @Id private Long id; @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private List<Child> children; } @Entity public class Child { @Id private Long id; @ManyToOne @JoinColumn(name = "parent_id") private Parent parent; } // Retrieving the parent entity Parent parent = entityManager.find(Parent.class, parentId); entityManager.detach(parent); // Attempting to access the children List<Child> children = parent.getChildren(); // This throws LazyInitializationException ``` In my application, I need to access the children of the parent after detaching it, but I need to seem to get them without working with exceptions. I tried fetching the parent with `JOIN FETCH`, but it negated the benefits of lazy loading for other parts of my application. Is there a way to efficiently handle detached entities while still maintaining performance? I've looked into using DTOs and projections, but they seem cumbersome for my use case. Any suggestions on best practices or design patterns to resolve this scenario would be greatly appreciated! This is part of a larger service I'm building. Has anyone else encountered this? I'm working on a REST API that needs to handle this. What would be the recommended way to handle this?