Spring Data JPA Native Query N + 1 problem



I’ve run into some code which behaviour is not clear for me.

We have first entity:

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

@OneToOne
@JoinColumn(name = "data_id")
private Data data;
    
}

and second one:

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

@Id
private Long dataId
    
}

And we have next method for retrieving data:

 @Query(value = "SELECT * FROM Info i inner join Data d on d.data_id=i.data_id", 
 nativeQuery = true)
 List<Info> getInfo() {}

As nativeQuery = true is present I expect this method make just one SQL select and retrieve me data. But If I take a look at logs actually there are 2 selects:

SELECT * FROM Info i inner join Data d on d.data_id=i.data_id;

SELECT * FROM Data d where d.data_id = 123;

Why this is happening ? How to fix it to make only one select and retrieve all data ?

Answer

It’s not possible to specify native query fetches without Hibernate specific APIs. I would suggest you to use a normal JPQL/HQL query:

@Query(value = "FROM Info i join fetch i.data")
List<Info> getInfo();

This will do the same as your native query but at the same time just run only a single query.



Source: stackoverflow