Home > Blockchain >  Spring Data JPA Native Query N 1 problem
Spring Data JPA Native Query N 1 problem

Time:09-17

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 ?

CodePudding user response:

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.

CodePudding user response:

Your Data entity column is not match with query you put in query is d.data_id but actual column name is dataId and nativeQuery = true is for Relational query not JPQL query

 @Query(value = "SELECT * FROM Info i INNER JOIN Data d ON d.dataId = i.data_id", 
 nativeQuery = true)
 List<Info> getInfo() {}
  • Related