Java 17: Conflict with Java Persistence API (JPA) and Custom Fetch Strategies in Spring Data
I've been working on this all day and I'm stuck on something that should probably be simple. After trying multiple solutions online, I still can't figure this out. I'm encountering an issue when using Spring Data JPA with Hibernate in my Java 17 application. I've defined a custom fetch strategy for a one-to-many relationship, but it seems like the data is not being fetched as expected. I have an `Order` entity that has a one-to-many relationship with an `OrderItem` entity. Here's a simplified version of my code: ```java @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToMany(mappedBy = "order", fetch = FetchType.LAZY) private List<OrderItem> items; } @Entity public class OrderItem { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne @JoinColumn(name = "order_id") private Order order; } ``` In my repository, I've tried using a custom query to fetch orders along with their items: ```java @Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id") Optional<Order> findByIdWithItems(@Param("id") Long id); } ``` However, when I call `findByIdWithItems`, I'm still getting a proxy object for the `Order` entity, and the `items` list appears to be empty â I have to explicitly access it in a way that triggers the fetch (e.g., iterating over it). I've also tried changing the fetch type in the `Order` entity to `FetchType.EAGER`, but that led to a distinct set of performance issues, loading all items for all orders in a single query. This is not scalable for my application since I have a large dataset. When debugging, I noticed that the Hibernate SQL log shows the fetch query being executed, but it's still not populating the list correctly. I'm using Spring Boot 2.5.4 and Hibernate 5.5.7.Final. Could this be related to how Hibernate handles proxies or lazy loading in conjunction with Spring? Is there a recommended way to improve the fetching strategy without sacrificing performance? Any insights would be appreciated! Any ideas what could be causing this? What's the best practice here? This issue appeared after updating to Java 3.10. Am I missing something obvious?