Spring Data JPA“找不到 PersistentEntity"用于列表<字符串> [英] Spring Data JPA "Couldn't find PersistentEntity" for List<String>
问题描述
很难弄清楚我是遇到了错误还是做了一些愚蠢的事情......
Having a hard time figuring out if i'm hitting a bug or doing something stupid...
Spring Boot v2.0.0.M7、spring-data-jpa、spring-data-rest、MySQL
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
)失败并显示以上.
statusCode is a varchar and Item
itself works as expected as an @Entity, but trying to project to a List of Strings (or List<Object>
) fails with the above.
如果重要的话,我故意不想在此处返回 Page
(不需要分页,因为预期的结果集很小).
If it matters, I intentionally don't want to return a Page<String>
here (no need to have paging since the expected resultset is small).
推荐答案
不能直接映射字符串.您将需要一个映射器对象.创建一个带有字符串字段的模型类 -
A String cannot be mapped directly. You will need a mapper object. Create a model class with a string field -
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;
}
}
然后更改查询以使用模型类 -
Then change the query to use the model class -
@Query("select new org.xyz.model.StringResult(DISTINCT item.statusCode as result) from Item item")
public List<StringResult> lookupStatusCodes();
这篇关于Spring Data JPA“找不到 PersistentEntity"用于列表<字符串>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!