Spring Data JPA&#34;无法找到PersistentEntity&#34;对于List <string>

时间:2018-01-18 14:35:36

标签: spring-boot spring-data-jpa

很难搞清楚我是在遇到错误还是做了些蠢事......

Spring Boot v2.0.0.M7,spring-data-jpa,spring-data-rest,MySQL

以下@Query

@Query("select DISTINCT item.statusCode from Item item")
public List<String> lookupStatusCodes();
PagingAndSortingRepository上的

正在抛出

java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class java.lang.String!
at org.springframework.data.mapping.context.PersistentEntities.lambda$getRequiredPersistentEntity$2(PersistentEntities.java:78) ~[spring-data-commons-2.0.2.RELEASE.jar:2.0.2.RELEASE]
at java.util.Optional.orElseThrow(Unknown Source) ~[na:1.8.0_151]
at org.springframework.data.mapping.context.PersistentEntities.getRequiredPersistentEntity(PersistentEntities.java:77) ~[spring-data-commons-2.0.2.RELEASE.jar:2.0.2.RELEASE]
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.wrap(PersistentEntityResourceAssembler.java:72) ~[spring-data-rest-webmvc-3.0.2.RELEASE.jar:3.0.2.RELEASE]

statusCode是一个varchar,而Item本身就像@Entity一样工作,但尝试投射到字符串列表(或List<Object>)失败了。

如果重要,我有意不想在这里返回Page<String>(因为预期的结果集很小,所以不需要分页)。

1 个答案:

答案 0 :(得分:1)

无法直接映射字符串。您将需要一个映射器对象。使用字符串字段创建模型类 -

package org.xyz.model;

import java.io.Serializable;

public class StringResult implements Serializable {

    private static final long serialVersionUID = 1L;
    private String result;

    public StringResult(
        String result) {
        super();
        this.result = result;
    }

    public String getResult() {
        return result;
    }
}

然后更改查询以使用模型类 -

@Query("select new org.xyz.model.StringResult(DISTINCT item.statusCode as result) from Item item")
public List<StringResult> lookupStatusCodes();