are there any pitfalls when return @Entity from @RestController instead of DTO ? like this:
@RestController public class EmployeeRestController { @Autowired private EmployeeRepository repository; @GetMapping("/rest/employee/get/{id}") public Employee getEmployeeByID(@PathVariable("id") int id) { return repository.retrieve(id); } @Entity public class Employee { ...
Advertisement
Answer
I’d say yes. By returning an entity, you are going to have tight coupling of your response contract and the database entity. So in future if you want to make modifications to either your response/entity, you might run into multiple issues. For example, let’s say, your Employee
entity has dateOfBirth
field, but your client wants you to send directly the age. You will have have to modify Employee
entity class and add business logic to it. So as the contract requirements change, so does your entity and this could result in multiple issues. Ideally you decouple the response/request contracts from your database entities. But of course, as always, it depends on how complex you believe your code could get.