Andy Dufresne
Andy Dufresne

Reputation: 6190

Passing parent id reference when creating child object through REST api

I am using spring boot (version - 2.1.1). I have a one to many database model exposed for CRUD operations through rest api's. The model looks as below. How do I configure the POST /departments api (that creates a department object) to accept just the organization id in the input json body?

@PostMapping
    public Long createDepartment(@RequestBody Department Department) {
        Department d = departmentService.save(Department);
        return d.getId();
    }

Note - I do not want to allow creating organization object when creating a department.

Model object mapping

@Entity
@Table(name="ORGANIZATIONS")
public class Organization{

    @Id
    @GeneratedValue
    Private long id;

    @Column(unique=true)
    Private String name;

    @OneToMany(mappedBy = "organization", fetch = FetchType.EAGER)
    private List<Department> departments;
}


@Entity
@Table(name="DEPARTMENTS")
Public class Department{

   @Id
   @GeneratedValue
   Private long id;

   @Column(unique=true)
   Private String name;

   @ManyToOne(fetch = FetchType.EAGER)
   private Organization organization;
}

Thanks!

Upvotes: 0

Views: 1293

Answers (1)

Tom
Tom

Reputation: 3850

The easiest and most sane way in my opinion is to utilize the DTO (Data Transfer Object) pattern.

Create a class that represent the model you want to get as your input:

public class CreateDepartmentRequest {
    private long id;

    // getters and setters
}

Then use it in your controller:

@PostMapping
public Long createDepartment(@RequestBody CreateDepartmentRequest request) {
    Department d = new Department();
    d.setId(request.getId());
    Department d = departmentService.save(d);
    return d.getId();
}

Side note, its better to ALWAYS return JSON through REST API (unless you use some other format across your APIs) so you can also utilize the same pattern as I mentioned above to return a proper model as a result of the POST operation or a simple Map if you don't want to create to many models.

Upvotes: 2

Related Questions