gpt4 book ai didi

spring-data-jpa - 如何绑定(bind)Spring Data REST实体来传输对象?

转载 作者:行者123 更新时间:2023-12-02 19:14:03 27 4
gpt4 key购买 nike

我们有两个具有客户端-服务器架构的 Spring Boot 应用程序。后端配置为Spring Data REST + JPA。前端应该使用后端公开的资源并提供公共(public) REST api。

是否可以让 Spring 数据通过声明(例如映射器 bean)自动从 DTO 映射域对象?

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

最佳答案

我们可以利用 Spring Data REST 中的投影功能(从 2.2.x 开始提供)。如下所示:

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

调用 REST 时,将“projection”参数设置为“orderDTO”,即

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

请引用:

注意:

  • 通过在 RepositoryRestResource 注解中设置 excerptProjection 属性,将默认返回投影,无需“projection”参数。
  • 当我们使用@Projection注释接口(interface)并将其放置在与域类型或其子包相同的包中时,需要“projection”。

关于spring-data-jpa - 如何绑定(bind)Spring Data REST实体来传输对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25906786/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com