【问题标题】:Spring boot JPA entitySpring Boot JPA 实体
【发布时间】:2020-07-04 10:03:41
【问题描述】:

我有一个名为 Order 的实体,它引用了一个名为 project 的实体,如下所示:

@Entity
@Table(name = "customer_order")
public class Order {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    @JoinColumn(name = "project_id", nullable = false)
    private Project project;

    @Column(name = "user_id")
    private String userId;

    @Column(name = "created_at")
    @CreationTimestamp
    private Date createdAt;
}

我的仓库如下:

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}

当我调用我的 rest get 端点来获取所有订单的列表时,在响应中,我在主订单对象中获得了一个项目对象,其中包含“项目”类的所有属性。我不想要这个。我需要一个仅包含它引用的项目 ID 的精益订单响应对象。我尝试在 Order 类中的“项目”属性上使用以下注释,但它完全摆脱了项目细节。

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)

我仍然需要关联项目的 ID。 我该怎么做?

【问题讨论】:

    标签: json spring-boot rest jpa


    【解决方案1】:

    我假设您的端点返回 JSON。

    在这种情况下,您将不得不编写自己的序列化程序。

    • 对于 Gson,这可以通过实现 JsonSerializer 并将其注册为类型适配器来实现
    • 对于 ObjectMapper (Jackson),您必须扩展 StdSerializer 并将其作为序列化程序添加到 ObjectMapper 或在模型类上使用注释 @JsonSerialize(using = ItemSerializer.class)

    【讨论】:

      猜你喜欢
      • 2020-10-30
      • 2018-06-21
      • 1970-01-01
      • 2017-11-24
      • 2017-12-11
      • 1970-01-01
      • 2023-03-28
      • 2016-12-03
      • 1970-01-01
      相关资源
      最近更新 更多