meursault
meursault

Reputation: 295

Spring Data dto projection method

I have a query in the below which is complicated but i need to project this DeploymentDto which method i can use for projection? This query is in interface class which extends JpaRepository. Later in another class i need to use resulting list in my code.

Basically i need to map my native query into dto, so for query like mine how can i do it? I did research but JPQL query for example uses simple native queries.

@Query(value = "SELECT a.name, a.created_at, a.updated_at, d.version, a.image, d.id, d.app_id\n" +
            "FROM applications a\n" +
            "LEFT JOIN deployments d ON d.app_id = a.id\n" +
            "WHERE d.app_id IS NULL\n" +
            "union\n" +
            "select a.name, d.created_at, d.updated_at, d.version, a.image, d.id, d.app_id from applications a\n" +
            "inner join deployments d on d.app_id = a.id\n" +
            "where d.updated_at = (\n" +
            "select max(d1.updated_at) from deployments d1 where d1.app_id = a.id)\n" +
            "ORDER BY name",  nativeQuery = true)
    List<Deployment> findLatestDeployments();

I cannot use directly it like List findLatestDeployments(); It gave an error like this:

{"timestamp":1595277133888,"message":"No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [com.gg.applications.model.DeploymentDto]"

Upvotes: 0

Views: 2377

Answers (1)

Robert Niestroj
Robert Niestroj

Reputation: 16131

If your DTO is a class you need to use @SqlResultSetMapping. I would however recommend to make your DTO a Interface and use this as a projection.

interface Deployment{
  public String name();
  public LocalDateTime created_at();
  public LocalDateTime updated_at();
  public long version();
  public byte[] image();
  public Long id();
  public Long app_id();
}

Upvotes: 1

Related Questions