Spring Data JPA Query using LEFT JOIN returns duplicate entities in Java 11 application
Hey everyone, I'm running into an issue that's driving me crazy. I'm encountering an issue with a Spring Data JPA query that utilizes a LEFT JOIN. The query is supposed to fetch a list of `Order` entities along with their associated `Customer` entities. However, the returned list contains duplicate `Order` entities. Hereβs the relevant part of my repository code: ```java public interface OrderRepository extends JpaRepository<Order, Long> { @Query("SELECT o FROM Order o LEFT JOIN o.customer c WHERE c.active = true") List<Order> findActiveCustomerOrders(); } ``` The `Order` entity has a many-to-one relationship with the `Customer` entity. When I call this method, I'm seeing that some `Order` entries are duplicated in the result set. I also noticed the following in my logs: ``` Hibernate: select o.id, c.id from order o left join customer c on o.customer_id = c.id where c.active = true ``` In my `Order` entity, I have: ```java @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "customer_id") private Customer customer; } ``` The `Customer` entity looks like this: ```java @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private boolean active; } ``` To address the duplicates, I've tried adding `DISTINCT` to my query: ```java @Query("SELECT DISTINCT o FROM Order o LEFT JOIN o.customer c WHERE c.active = true") ``` However, this hasn't resolved the issue. The duplicates seem to arise because there can be multiple `Order` records linked to a single `Customer`. Is there a better way to structure my query or perhaps a different approach to eliminate these duplicates? I'm using Spring Boot 2.5 and Hibernate 5.4 with Java 11. Any insights would be greatly appreciated! I recently upgraded to Java 3.9. Am I approaching this the right way?