Spring Data Jpa 投影(Projection)的用法

之前关联查询的时候返回几个字段的时候我用到的返回方式是创建一个VO利用构建方法进行赋值返回的

 

 

 

 现在也可以使用投影的方式获取

import org.springframework.beans.factory.annotation.Value;

public interface GenericProjection {

    @Value("#{target.identifier}")
    String getIdentifier();

    @Value("#{target.value}")
    String getValue();

    @Value("#{target.recordType}")
    String getRecordType();

    @Value("#{target.description}")
    String getDescription();
}

repository

 @Query("select d.identifier as identifier, d.value as value,d.recordType as recordType,h.description as description from GenericConfigDetails d ,GenericConfigHeaders h where d.recordType = h.recordType and d.recordType=?1 and d.active='Y' ")
    List<GenericProjection> findProjectionByRecordType(String recordType);

 

 

 

 

注意:记得要加as起别名,不然@Value 的target获取不到值,不起的时候我试了一下报以下的错

"status": 500,
"error": "Internal Server Error",
"message": "Could not write JSON: EL1008E: Property or field 'value' cannot be found on object of type 'org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap' - maybe not public or not valid?; nested exception is com.fasterxml.jackson.databind.JsonMappingException: EL1008E: Property or field 'value' cannot be found on object of type 'org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap' - maybe not public or not valid? (through reference chain: com.znstms.core.response.JsonResponseExt[\"data\"]->java.util.ArrayList[0]->com.sun.proxy.$Proxy186[\"value\"])",
"path": "/test/test1"
}

 

 

 

 

 

 

 

posted @ 2019-12-12 16:41  零落星尘  阅读(3553)  评论(0编辑  收藏  举报