java SpringBoot @OneToMany触发器错误和请求发送错误

w3nuxt5m  于 2023-04-04  发布在  Java
关注(0)|答案(2)|浏览(125)

我有两个实体类。一个员工应该有一个部门。但是一个部门可以有很多员工。
当我发送给 Postman 请求插入员工时,我想触发Department表。

@Table
@Entity(name = "employee")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee extends Auditable<String> implements Serializable {

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

    @Column(name = "employee_name", nullable = false)
    private String employeeName;

    @Column(name = "employee_surname", nullable = false)
    private String employeeSurname;

    @Column(name = "employee_email",
            nullable = false,
            unique = true)
    private String employeeEmail;

    @Column(name = "employee_identity_number",
            nullable = false,
            unique = true,
            length = 11)
    private String employeeIdentityNumber;

    @ManyToOne
    @JoinColumn(name = "department_id")
    private Department department;

}

上面的代码是我的Employee类。

@Table
@Entity(name = "department")
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Department {

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

    @Column(name = "department_name", unique = true)
    private String departmentName;

    @OneToMany(mappedBy = "department")
    private Set<Employee> employees;

}

以上代码我系类。
当我像下面这样以JSON格式发送 Postman 请求时,

{
    "employeeName": "Josh",
    "employeeSurname": "Long",
    "employeeEmail": "joshlong@gmail.com",
    "employeeIdentityNumber": "12345678912",
    "department": 1
}

我知道,部门属性是错误的。我应该定义为部门对象。但我想只发送部门ID。
当我发送这个请求时,我想触发部门表中的雇员字段。

rekjcdws

rekjcdws1#

你可以有一个这样的dto对象

public class EmployeeDto{
    private String employeeName;
    private String employeeSurname;
    private String employeeEmail;
    private String employeeIdentityNumber;
    private long departmentId;
}

控制器方法如下:

@PostMapping("employee")
public Employee save(@RequestBody EmployeeDto employeeDto){
    Employee em = employeeDto.toEntity();
    //Assuming department with given id already exist
    em.setDepartment(Department.builder().departmentId(employeeDto.departmentId).build());
    return emRepository.save(employee);
}

据我所知,这应该能起到作用。

kq4fsx7k

kq4fsx7k2#

你可以试试这个

{
   "employeeName": "Josh",
   "employeeSurname": "Long",
   "employeeEmail": "joshlong@gmail.com",
   "employeeIdentityNumber": "12345678912",
   "department": {"departmentId": "5342432432"}
}

对于部门,

{
   "departmentName": "department", 
   "employees" : [{"id" : "79878"}, {"id": "654654"}, ...]
}

相关问题