Hibernate 5.4: Issues with FetchType.LAZY causing TooManyResultsException in a One-to-One Relationship
I'm getting frustrated with I'm encountering a `TooManyResultsException` when trying to fetch an entity that has a one-to-one relationship with another entity configured with `FetchType.LAZY`. The relationship is correctly set up, but when I load the parent entity and subsequently access the child entity for the first time, it results in this exception. Here's a simplified version of my entity classes: ```java @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; @OneToOne(fetch = FetchType.LAZY, mappedBy = "user") private Profile profile; } @Entity public class Profile { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne @JoinColumn(name = "user_id") private User user; } ``` I am using Hibernate 5.4 with Spring Boot and MySQL. When I perform a query to retrieve a `User`, I use the following code: ```java User user = userRepository.findById(userId).orElse(null); Profile profile = user.getProfile(); // This line triggers the fetch ``` I have also verified that the database contains the user and profile records, and they are linked correctly. However, the first time I access `user.getProfile()`, I get the following stack trace: ``` org.hibernate.TooManyResultsException: query did not return a unique result: 2 ``` I've tried including `@Transactional` on the service layer method that performs this retrieval, but that doesn't seem to help. Additionally, I considered using `FetchType.EAGER` but I want to avoid the performance penalties associated with that. Is there a way to resolve this issue without changing the fetch type to eager? What could be causing Hibernate to think there are multiple results when there should only be one? This is my first time working with Java 3.10. Cheers for any assistance! I've been using Java for about a year now.