【问题标题】:Post JSON with @ManyToOne Relationship in Spring Boot在 Spring Boot 中使用 @ManyToOne 关系发布 JSON
【发布时间】:2019-10-01 15:59:34
【问题描述】:

我在 Spring Boot 中编写了一个测试应用程序。员工与部门有关系。 CRUD 有效,但我不确定我的做法是否正确。

当我要创建一个新员工时,我必须发送以下帖子请求

    "id": 3,
    "firstname": "John",
    "lastname": "Doe",
    "salary": 50000,
    "department": {
        "id": 2,
        "name": "Sales"
    } 
}

这是员工类:

@Entity
public class Employee {
    @Id
    @GeneratedValue
    private Long id;
    private String firstname;
    private String lastname;

        @ManyToOne(cascade = CascadeType.ALL)
        @JoinColumn(name = "department_id", referencedColumnName="id")
    private Department department;
    private int salary;

这是 EmployeeController 中的 create 方法:

    @PostMapping("/employees")
    public Employee create(@RequestBody Employee employee) {
        return employeeService.add(employee);
    }

部门条目已存在。 是否可以在不填写完整关系的情况下创建员工 (部)? 我只想添加部门ID。但是如果我这样做,json数据中的name字段为空(获取请求)

id  3
firstname   "John"
lastname    "Doe"
department  
  id    2
  name  null
salary  50000

有没有更好的方法?

【问题讨论】:

    标签: json spring rest spring-boot jpa


    【解决方案1】:

    您将实体作为请求主体,这不是正确的方法。您可以将 Some VO 作为请求对象,然后在服务中转换为实体。 例如

    EmployeeVO{
    private String firstname;
    private String lastname;
    List<Integer> departments;
    }
    

    此外,您可以使用 Jackson 注释,例如 @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) 忽略未知属性并包含非空属性。

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 2021-08-17
      • 2021-06-15
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      相关资源
      最近更新 更多