I have a Post method in my restApi in which i am mapping JSON to the Bean using @RequestBody. here is my code for the controller where i map my JSON to Employee bean
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private EmployeeService employeeService;
public EmployeeController(EmployeeService employeeService) {
super();
this.employeeService = employeeService;
}
//build restAPi for create Employee
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee){
return new ResponseEntity<Employee>(employeeService.saveEmployee(employee),HttpStatus.CREATED );
}
}
Below is the Employee bean class
@Data
@Entity //makes this as JPA entity
@Table(name="employee") // if not defined it creates the table with class name by default
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name="email_id")
private String emailId;
}
Also, this is my Service class
@Override
public Employee saveEmployee(Employee employee) {
// TODO Auto-generated method stub
return employeeRepository.save(employee);
}
the JSON request i post to this service is as follows
{
"firstName" : "Priya",
"lastName" : "Venkatesan",
"emailId" : "[email protected]"
}
I am not sure what i am missing and i am new for API development. Please request help. Thanks
CodePudding user response:
It's not good idea to use persistence entity in @RequestBody of the controller.
Please check out this link: Should entity class be used as request body
CodePudding user response:
My idea about the issue : You are using lombok in your jpa entity. You might have a problem with Lombok and your getters/setters are not generated, which make it impossible to map your json & your Employee object.