之前關聯查詢的時候返回幾個字段的時候我用到的返回方式是創建一個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" }