Запросы в RepositoryRestResource - PullRequest
1 голос
/ 05 января 2020

При использовании Spring Data Rest с последней версией Spring Boot у меня возникают проблемы с извлечением результатов запроса, если результат не идентичен сущности. Я уменьшил класс до минимума, поэтому вот он:

@RepositoryRestResource
public interface UserRepository extends JpaRepository<User, Integer> {
   @Query("select u from User u left join Customer c on u.customer=c")
   Page<?> extractOnlyUsers(Pageable pageable);

   @Query("select u, c from User u left join Customer c on u.customer=c")
   Page<?> extractUsersAndCustomers(Pageable pageable);
}

Первый запрос REST (extractOnlyUsers) работает правильно, а второй запрос extractUsersAndCustomers выдает эту ошибку:

"Не удалось найти PersistentEntity для класса типов [L java .lang.Object;!"

Ошибка кажется усеченной, и это не поможет, если я установлю уровень журнала на DEBUG.

Я почти уверен, что должен предоставить какой-то конвертер, но я не знаю как. Вот мои вопросы:

  1. Как мне указать Spring для сериализации результатов запроса? Нужно ли производить конвертеры для всех запросов?
  2. Мне кажется, ошибка обрезана, есть ли способ просмотреть полное сообщение?

Я включаю полное сообщение об ошибке:

2020-01-05 19:23:06.836 DEBUG 8378 --- [nio-8001-exec-8] org.hibernate.SQL                        : select count(user0_.id) as col_0_0_ from "user" user0_ left outer join "customer" customer1_ on (user0_."customer_id"=customer1_.id)
Hibernate: select count(user0_.id) as col_0_0_ from "user" user0_ left outer join "customer" customer1_ on (user0_."customer_id"=customer1_.id)
2020-01-05 19:23:06.839 DEBUG 8378 --- [nio-8001-exec-8] org.hibernate.loader.Loader              : Result set row: 0
2020-01-05 19:23:06.840 DEBUG 8378 --- [nio-8001-exec-8] org.hibernate.loader.Loader              : Result row: 
2020-01-05 19:23:06.840 DEBUG 8378 --- [nio-8001-exec-8] .m.m.a.ExceptionHandlerExceptionResolver : Using @ExceptionHandler org.springframework.data.rest.webmvc.RepositoryRestExceptionHandler#handleMiscFailures(Exception)
2020-01-05 19:23:06.840 ERROR 8378 --- [nio-8001-exec-8] o.s.d.r.w.RepositoryRestExceptionHandler : Couldn't find PersistentEntity for type class [Ljava.lang.Object;!

java.lang.IllegalArgumentException: Couldn't find PersistentEntity for type class [Ljava.lang.Object;!
    at org.springframework.data.mapping.context.PersistentEntities.lambda$getRequiredPersistentEntity$2(PersistentEntities.java:96) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
    at java.base/java.util.Optional.orElseThrow(Optional.java:401) ~[na:na]
    at org.springframework.data.mapping.context.PersistentEntities.getRequiredPersistentEntity(PersistentEntities.java:95) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.wrap(PersistentEntityResourceAssembler.java:72) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.toModel(PersistentEntityResourceAssembler.java:55) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.toModel(PersistentEntityResourceAssembler.java:38) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.web.PagedResourcesAssembler.createModel(PagedResourcesAssembler.java:211) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
    at org.springframework.data.web.PagedResourcesAssembler.toModel(PagedResourcesAssembler.java:123) ~[spring-data-commons-2.2.3.RELEASE.jar:2.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.AbstractRepositoryRestController.lambda$entitiesToResources$3(AbstractRepositoryRestController.java:97) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at java.base/java.util.Optional.orElseGet(Optional.java:362) ~[na:na]
    at org.springframework.data.rest.webmvc.AbstractRepositoryRestController.entitiesToResources(AbstractRepositoryRestController.java:97) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.AbstractRepositoryRestController.toCollectionModel(AbstractRepositoryRestController.java:80) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.RepositorySearchController.lambda$toModel$1(RepositorySearchController.java:206) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at java.base/java.util.Optional.map(Optional.java:258) ~[na:na]
    at org.springframework.data.rest.webmvc.RepositorySearchController.toModel(RepositorySearchController.java:203) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at org.springframework.data.rest.webmvc.RepositorySearchController.executeSearch(RepositorySearchController.java:187) ~[spring-data-rest-webmvc-3.2.3.RELEASE.jar:3.2.3.RELEASE]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.2.RELEASE.jar:5.2.2.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
    at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

2020-01-05 19:23:06.841 DEBUG 8378 --- [nio-8001-exec-8] o.s.w.s.m.m.a.HttpEntityMethodProcessor  : Using 'application/json;q=0.8', given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8] and supported [application/json, application/*+json, application/json, application/*+json]

Если это поможет, мои сущности:

@Entity 
@Getter 
@Setter 
@NoArgsConstructor 
@AllArgsConstructor 
@Table(name = "`customer`") 
public class Customer {
    @Id
    @GeneratedValue(generator = "customer_generator")
    int id;

    String name;

    Boolean enabled; 
}

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "`user`")
public class User {
    @Id
    @GeneratedValue(generator = "user_generator")
    int id;

    String userName;

    @JsonIgnore
    String hashedPassword;

    @ManyToOne(fetch = FetchType.EAGER)
    Customer customer;

    Boolean enabled = true;
}

Я также попробовал это:

@Query("select new dto.UserDetails(u, c) from User u left join Customer c on u.customer=c")
List<dto.UserDetails> extractUsersAndCustomers(Pageable pageable);

С этой сущностью:

@Getter
public class UserDetails {

    private final int id;
    private final Boolean enabled;
    private final String userName;
    private final Integer customerId;
    private final String customerName;

    public UserDetails(User user, Customer customer) {
        this.id= user.getId();
        this.enabled = user.getEnabled();
        this.userName = user.getUserName();
        if (customer != null) {
            this.customerId = customer.getId();
            this.customerName = customer.getName();
        } else {
            this.customerId = null;
            this.customerName = null;
        }
    }
}

Ошибка I ' получено:

Не удалось найти PersistentEntity для класса типа dto.UserDetails

...