Home > database >  are there any pitfalls when return @Entity from @RestController instead of DTO?
are there any pitfalls when return @Entity from @RestController instead of DTO?

Time:10-13

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 {
...

CodePudding user response:

What you are doing is absolutely fine. There is no any pitfalls behind.

CodePudding user response:

No there aren't any . You can return an entity the spring boot will covert your entity into Json object

CodePudding user response:

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.

  • Related