I can save two entity on one post request all done but how can i pass more than one argument in ResponseEntity<T>
while returning in rest-api. I am new in rest-api
.
Here down is my code for Controller:
@RequestMapping(value="/coursebook", method=RequestMethod.POST)
public ResponseEntity<Course> saveCourseBook(@RequestBody Course course, @RequestBody Book book)
{
try {
Course saveCourse = this.pojoService.addCourseBook(course);
Book saveBook = this.pojoService.addBookAuthor(book);
return ResponseEntity.ok(saveCourse); // Here i want to add `saveBook` also for json response.
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
CodePudding user response:
The response class that you are trying to send back can have any number of fields. You can have a generic response class like this.
Response
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Response<T,K> {
private T courseResponse;
private K bookResponse;
}
Once this is done, you can modify the controller as
@RequestMapping(value="/coursebook", method= RequestMethod.POST)
public ResponseEntity<Response<Course, Book>> saveCourseBook(@RequestBody Course course, @RequestBody Book book)
{
try {
Course saveCourse = this.pojoService.addCourseBook(course);
Book saveBook = this.pojoService.addBookAuthor(book);
return ResponseEntity.ok(new Response<>(
saveCourse,
saveBook
));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
Or, you can get in a CourseResponseDTO
class to do the same.
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class CourseResponseDTO {
private Course course;
private Book book;
}
@RequestMapping(value="/coursebook", method= RequestMethod.POST)
public ResponseEntity<CourseResponseDTO> saveCourseBook(@RequestBody Course course, @RequestBody Book book)
{
try {
Course saveCourse = this.pojoService.addCourseBook(course);
Book saveBook = this.pojoService.addBookAuthor(book);
return ResponseEntity.ok(new CourseResponseDTO(
saveCourse,
saveBook
));
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}