I’m encountering an issue with lazy loading in my Spring Boot application. When I use FetchType.LAZY on a @ManyToOne relationship, I’m unable to fetch the associated entity, and I get an error indicating that the entity with a specific ID cannot be found. However, when I switch to FetchType.EAGER, the problem disappears in the part of the code where I’m currently working, but it breaks another previously implemented section, causing the same error.
Entities
Here are the two entities involved in this relationship:
XEntity
@Entity
@Table(name = "x")
public class xEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nom", nullable = false)
private String nom;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_y", referencedColumnName = "id", nullable = false)
private yEntity yEntity;
// Getters and setters
}
yEntity
@Table(name = "y")
public class yEntity{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "theme_groupe_id_generator_seq")
@SequenceGenerator(name = "theme_groupe_id_generator_seq", sequenceName = "theme_groupe_id_seq", allocationSize = 1)
@Column(name = "id", nullable = false)
private Integer id;
@OneToMany(mappedBy = "yEntity", cascade = CascadeType.ALL, orphanRemoval = true)
private List<xEntity> themes;
// Getters and setters
}
Problem Description
When I try to access the yEntity from xEntity with FetchType.LAZY, I get the following error:
Unable to find fr.gouv.isidor.importation.infra.database.entity.themes.ThemeGroupeEntity with id 4
What I’ve Tried
- Ensuring the session is open using @Transactional on every method that call the repository.
- Using Hibernate.initialize() to force initialization. Verified that the
entity with the given ID exists in the database. - Tried with FetchType.EAGER, which works in the current part of the code but
causes the same issue in another section (in this case the code works with LAZY and doesn’t with EAGER).
For calling the xEntity in the first case (who are working with EAGER and doesn’t with LAZY) i’m using native jpa findById(Integer id).
For calling the xEntity in the second case (who art workin with LAZY and doesn’t with EAGER) i’m using nativ jpa findByName(String name).
How can I properly configure lazy loading for the ThemeGroupeEntity association in ThemeEntity to avoid this error? Any insights or solutions would be greatly appreciated.