Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA "Couldn't find PersistentEntity" for List<String> [duplicate]

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

The following @Query

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

on a PagingAndSortingRepository is throwing a

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 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.

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).

like image 929
jamey graham Avatar asked Nov 07 '22 11:11

jamey graham


1 Answers

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();
like image 140
harsh tibrewal Avatar answered Nov 23 '22 09:11

harsh tibrewal