6

We have two Spring Boot applications with a client-server architecture. The backend is configured with Spring Data REST + JPA. The front end should consume the resources exposed by the backend and serve a public REST api.

Is it possible to have Spring data map the domain objects automatically from DTOs by declaring, e.g., a mapper bean?

// JPA persistable
@Entity
public class Order { .. }

// Immutable DTO
public class OrderDto { .. } 

// Is this somehow possible..
@RepositoryRestResource
public interface OrderDtoRepository extends CrudRepository<OrderDto, Long> {}

// .. instead of this?
@RepositoryRestResource
public interface OrderRepository extends CrudRepository<Order, Long> {}
RJo
  • 15,631
  • 5
  • 32
  • 63

1 Answers1

3

We can make use of Projection feature (available from 2.2.x onwards) in Spring Data REST. Something like below:

import org.springframework.data.rest.core.config.Projection;

@Projection(name = "orderDTO", types = Order.class)
public interface OrderDTO {
    //get attributes required for DTO
    String getOrderName();
}

@RepositoryRestResource(excerptProjection = OrderDTO.class)
public interface OrderRepository extends CrudRepository<Order, Long> {
}

When calling REST set "projection" parameter to "orderDTO" i.e

http://host/app/order?projection=orderDTO

Please refer:

Note:

  • By setting excerptProjection attribute in RepositoryRestResource annotation, it will return projection by default without "projection" parameter.
  • "projection" is required when we annotate the interface using @Projection and place it in the very same package as the domain type or a subpackage of it.
Community
  • 1
  • 1
charybr
  • 1,888
  • 24
  • 29
  • This is not exactly what I was after, since I'm looking more like a "default" projection without having to give the projection parameter, but since no better answers were given, I marked it as correct – RJo Dec 18 '14 at 08:56
  • 1
    By setting excerptProjection attribute in RepositoryRestResource annotation, it will return projection by default without "projection" parameter. – charybr Dec 19 '14 at 07:43
  • Note that excerptProjection doesn't work (by design) for single item resources, only for collection resources: http://stackoverflow.com/questions/30220333/why-is-an-excerpt-projection-not-applied-automatically-for-a-spring-data-rest-it – Devabc Nov 22 '15 at 23:17