0

I have the following endpoint:

    @PostMapping
    Employee createEmployee(@Valid @RequestBody Employee newEmployee, BindingResult bindingResult) {
        return employeeRepository.save(newEmployee);
    }

I can send POST requests as JSON and have an employee created, but how do I link associated entities, such as a Department entity?

When I send a post request, it looks like this (I know it's not valid JSON, it's just browser console output):

departmentId: 1
emailAddress: "dillon@james.com"
firstName: "Dillon"
lastName: "James"
phoneNumber: undefined

The department exists in my database, and has an ID of 1. I thought that Spring would automatically set the departmentId somehow on my Employee model, but it doesn't seem to do that, or I must be missing something.

I'm basically trying to set the department of the newly created employee, but how I have it currently doesn't seem to do so.

For reference, this is how my Employee entity is defined:

@Entity
@Getter
@Setter
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    private String firstName;

    @NotNull
    private String lastName;

    @NotNull
    @Column(unique = true)
    private String emailAddress;

    @ManyToOne
    private Department department;

    private String phoneNumber;
}
Blaine Lafreniere
  • 2,584
  • 23
  • 41
  • Look up the department by id and set it manually? (Also, your json is missing a lot of quote marks, and ‘undefined’ isn’t valid json as a literal.) – BeUndead May 14 '21 at 02:15
  • @BeUndead I don't know how to get the `departmentId` from within the scope of the controller endpoint. I have called the debugger and inspected every possible variable within that scope, and I don't see it. I copied the "JSON" from the browser console, just to show what data is present, I know it's not valid, but in the context of the React app that I'm sending the request from, I promise it's valid. – Blaine Lafreniere May 14 '21 at 02:19
  • Ah, in which case the answers to https://stackoverflow.com/q/12893566/2478398 should give a few options. – BeUndead May 14 '21 at 02:23
  • @BeUndead Sweet, thanks for that, that explains a lot. – Blaine Lafreniere May 14 '21 at 02:33

0 Answers0