Modify SQL query generated behind Spring Data REST projections

天涯浪子 提交于 2019-11-29 10:59:10

问题


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


回答1:


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




回答2:


I think you can use "nested projections", let's say.

An example: resource A contains field bubi and resource B, which has field foo, bar, zed.

You should create a projection for B where you list just the fields you want:

@Projection(name="reduced", types = B.class)
public interface BReduced {
    String foo;
    //exclude bar, for instance
    int zed;
}

Then you use that projection in A's projection.

@Projection(name="reduced", types = A.class)
public interface AReduced {
    int bubi;
    BReduced b;
}

Have I undestood well, or were you talking about performance in SQL query?



来源:https://stackoverflow.com/questions/26524529/modify-sql-query-generated-behind-spring-data-rest-projections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!