【问题标题】:Ignore property in nested object of the same type with Spring Boot忽略与 Spring Boot 相同类型的嵌套对象中的属性
【发布时间】:2021-10-30 01:22:06
【问题描述】:

我有一个实体类,它使用与属性相同的类:

@Entity
public class Employee {
      private String name;
      @OneToOne
      @JoinColumn(name = "supervisor_id", referencedColumnName = "id")
      private Employee supervisor;
      //getters and setters
}

我想获得员工的主管,但不是主管的主管。我能以某种方式解决这个问题吗?

{
   "name": "PersonName",
   "supervisor": {
       "name": "Supervisor name",
       "supervisor": null // i don't want this one
   }
}

【问题讨论】:

  • 使用 DTO,这样您就可以定义您想要什么和不想要什么。
  • 您希望在 JSON 中排除“主管”属性?还是在实体中?
  • 最后我使用了嵌套类,但是我复制了属性。至少它干净简单。

标签: spring-boot hibernate jpa spring-data-jpa


【解决方案1】:

只需忽略 Json 中的空值。以下对我有用:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.persistence.*;

@Getter
@Setter
@ToString
@Entity
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class Employee {

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

    private String name;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "supervisor_id", referencedColumnName = "id")
    private Employee supervisor;
}

这是测试

@Test
public void test2() throws Exception {
    Employee employee = makeEmployee("employee 1");
    Employee supervisor1 = makeEmployee("supervisor 1");
    employee.setSupervisor(supervisor1);

    Employee save = employeeRepository.save(employee);

    System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(save));
}

这是我的测试输出:

{
  "id" : 1,
  "name" : "employee 1",
  "supervisor" : {
    "id" : 2,
    "name" : "supervisor 1"
  }
}

确保您使用正确的 JsonSerialize org.codehaus.jackson.map.annotate.JsonSerialize 而不是 com.fasterxml.jackson.databind.annotation.JsonSerialize

【讨论】:

    【解决方案2】:

    最后,我只对 dto 和需要字段的实体使用了嵌套类。 确实我复制了类的属性,但至少它是干净和简单的。

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2014-05-06
    • 1970-01-01
    • 2015-10-14
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多