'Spring Framework request body best practice
I've been thinking about what is the best way to consume request body.
We need to save a student and we have these classes.
@Entity
@Table(name = "student")
class StudentEntity {
private String name;
// getter, setter
}
class StudentDTO {
private final String name;
// getter
}
record StudentRecord(String name) {}
record CreateStudentRequest(String name) {}
Which one of these controller methods is the best/good way to do that.
@PostMapping("/student")
void consumeWithEntityClass(@RequestBody StudentEntity entity) {
// do something
}
@PostMapping("/student")
void consumeWithDTOClass(@RequestBody StudentDTO dto) {
// do something
}
@PostMapping("/student")
void consumeWithRecord(@RequestBody StudentRecord record) {
// do something
}
@PostMapping("/student")
void consumeWithNamedRecord(@RequestBody StudentCreateRequest request) {
// do something
}
I think the worst way is using Entity class. Consumer may have write access to some fields.
In my humble opinion, using consumeWithNamedRecord is the best. Each endpoint have different request classes is the way better. Because you contract with the consumer, you should't change field names or types. But i've some issues on it.
Is record classes well-suited for these situations?
Where should I put these classes, inside the controller class as inner class?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
