Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring Data JPA projection optimize the sql?

Spring boot: 1.5.10 spring Data JPA : 1.11.10

IE MyEntity

 class MyEntity{
     private Long id;
     private String name;
     private Integer age;
    // getter setter
 }

My MyProjection

 interface MyProjection{ String getName() }

MyEntityRepository

 ...
  MyProjection findById(Long Id)
  ...

when I call the findById function, the generate sql is:

 select myentity0_.id, myentity0_.name,myentity0_.age from MyEntity myentity0_ where ...

Why it also select the age column ?

like image 719
John Zhang Avatar asked Nov 28 '25 16:11

John Zhang


1 Answers

Yes, Spring Data JPA should only select the specific columns it needs when dealing with interface projections.

I have just tested it in a simple project based on your question and have observed the following query being executed:

select myentity0_.name as col_0_0_ from my_entity myentity0_ where myentity0_.id=?

This would suggest that you application is behaving differently. Have a look at the sample project and compare it to your own to see if you can spot any differences: https://github.com/roberthunt/spring-data-interface-projection

like image 134
Robert Hunt Avatar answered Dec 01 '25 07:12

Robert Hunt