Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify SQL query generated behind Spring Data REST projections

EDIT : How to Keep only needed columns in SELECT for Spring Data Rest Projections?

Spring Data Rest Projections are good for getting a subset of columns for links which are generated, but the Query that gets generated in behind still has all columns in it.

How can Projections be created where also SQL queries have only those columns in SELECT which are in Projection

like image 449
fortm Avatar asked Feb 11 '26 07:02

fortm


1 Answers

I don't know why it's missing from the docs, but this spring sample (from spring) shows that you can use projections as the return type for a @Query. So you can do:

public interface ActionId {
    String getId(); 
}

@Query("select a.id as id from Action a where a.type = :type")
public List<ActionId> findByType(@Param("type") String type);

Now instead of having to use constructor expressions, you can more succinctly just select the columns you want, and return an object. I wish that projections could be applied to the domain object itself, so you could still return an "Action" with just the id field, but that doesn't look possible now-

ref:https://github.com/spring-projects/spring-data-examples/blob/master/jpa/example/src/main/java/example/springdata/jpa/projections/CustomerRepository.java

like image 76
chrismarx Avatar answered Feb 13 '26 00:02

chrismarx