0

Custom Project interface for selecting only required fields of main table and reference entities.

public interface SimpleProjection{
   Long getId();

   interface Location{
     Long getId();
   }
   interface Address{
     String getCity();
   }
}

Entities

@Entity
public class Simple{
 @Id
 private Long id;
 @OneToOne
 Location mainLocation;
 @OneToOne
 Location tempLocation;
}

@Entity
public class Location{
 @Id
 private Long id;
 private String name;
 //many more
}

Spring Repository

public interface SimpleRepository extends JpaRepository<Simple, Long> {
  Optional<SimpleProjection> getById(Long id);
}

While I invoking getById() method on repository, it fetches all the column of related entities instead of defined one.

Please feel free to suggest better approach for projection as I have many related entites when I used simpler approach without projection around 200 columns get fetched that's why I am using Projection approach.

K.Nicholas
  • 10,956
  • 4
  • 46
  • 66
Gaurav Srivastav
  • 2,381
  • 1
  • 15
  • 18
  • Perhaps put a @Query that returns only the stuff you want? – K.Nicholas Oct 03 '18 at 18:42
  • Possible duplicate of [Spring JPA selecting specific columns](https://stackoverflow.com/questions/22007341/spring-jpa-selecting-specific-columns) – K.Nicholas Oct 03 '18 at 18:45
  • I don't want it through @Query – Gaurav Srivastav Oct 04 '18 at 02:36
  • maybe you should edit your question then. – K.Nicholas Oct 04 '18 at 02:47
  • I have edited the question – Gaurav Srivastav Oct 04 '18 at 15:05
  • Documentation says: `The query execution engine creates proxy instances of that interface at runtime for each element returned and forwards calls to the exposed methods to the target object.`. I think, while you debugging, you can see all columns, but you can't extract them from proxy. – Valijon Oct 04 '18 at 15:56
  • I have seen the executed query using show_sql=true, it fetches all the columns of reference entities. Like If I have defined sub interface with getter method of required columns but instead of fetching only those columns it fetches almost every column for that entity e.g Location. – Gaurav Srivastav Oct 04 '18 at 16:52

0 Answers0