Search code examples
javahibernatejpaspring-data-jpajpql

ManyToOne relationship still getting eagerly fetched


I have read here that By default, the JPA @ManyToOne and @OneToOne annotations are fetched EAGERLY.

My project is Spring Boot and uses Jackson.

My entities is getting fetched eagerly despite being annotated with lazy when I view the entities in the browser:

@Entity
@Data
@Table(name="HEALTH_CHECK")
public class HealthCheck {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @JsonManagedReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private Bird bird;

And on Bird:

@Entity
@Data
public class Bird {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    @JsonBackReference
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "bird")
    private List<HealthCheck> listHealthCheck = new ArrayList<>();
    //others

I have tried using the derived query for findById and rolling my own:

@Query("SELECT h FROM HealthCheck h WHERE h.id = :id")
Optional <HealthCheck> getOneManually(@Param("id") Long id);

Either way a query on HealthCheck returns all the details of a bird.

Shouldn't my @ManyToOne(fetch = FetchType.LAZY, optional = false) on HealthCheck override the default EAGER fetching?


Solution

  • The ManyToOne will be fetched lazily in your case - no doubts. The question is what your code is doing with the fetched entity HealthCheck. If it calls toString() or serialize a JSON string or you are showing the object in the IDE debugger window - all of this will cause Hibernate to fetch the Bird entity from the database with an additional select.

    This is how lazy loading works - not fetch initially but fetch as soon as any getter called.