Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring REST: Get JSON data from Request body in addition to entity

I'm working with java project using spring REST.

My problem that i could not extract data from request body (which is json) after receive it as enitiy.

for example:

JSON Request Body

{
    "firstname": "Rayan",
    "lastname": "Cold",
    "company_id": 23
}

My Controller maaped method is:

@PostMapping("/employee")
public Employee createEmployee(@RequestBody Employee employee) {

    // Here i need to extract the company id from request body
    // Long companyId = *something* // how i can extract from request ?

    return companiesRepository.findById(companyId).map(company -> {
        employee.setCompany(company);
        return employeeRepository.save(employee);
    }).orElseThrow(() -> new ResourceNotFoundException("Company not found"));
}

I know i can pass company ID as path variable. But i do want it in request body not in URI.

Thanks

like image 636
Mohammad Ahmad Avatar asked Nov 21 '25 13:11

Mohammad Ahmad


1 Answers

company_id can not be mapped if your Employee class contains companyId.

I guess your company class like:

public class Employee {

private String firstname;
private String lastname;
private Long companyId;

//skip getter setter }

change it to :

public class Employee {

private String firstname;
private String lastname;
@Transient
@JsonProperty("company_id")
private Long companyId;

//skip getter setter }

like image 85
GolamMazid Sajib Avatar answered Nov 24 '25 03:11

GolamMazid Sajib