Search code examples
spring-boothibernaterestjpadto

Expose custom query in Spring Boot Rest API with multiple joins


I have an Spring REST Api and a MySQL Database, now I would like to expose the result of an custom query with multiple joins. I have tried multiple suggestions that I found online but none of them were working for me so far. What I want to do is something like a read only DTO that has all the fields of my custom query so that in the end I have one api page exposing the DTO data as JSON so my client (Angular) can read the data from there. I already tried to:

  • create an @RestController with an injected EntityManager that executes a NativeQuery and then populates the DTO with the returned data but since my DTO is no Entity I get an Hibernate Mapping Exception

  • create a custom Repository and its Impl but with a similar outcome

  • place the Query inside an existing @Entity that is part of the Query statement

What am I missing here? Do I have to annotate my DTO maybe? Cuttently it's just a POJO, I think the @Entity annotation is not the right thing here since I don't want a Table created from my DTO.


Solution

  • Fixed it by letting the Query return an Array of type Object and afterwards mapping it to the DTO Constructor.