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> {}
4

1 回答 1

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.
于 2014-11-05T14:30:35.853 回答