0

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 {
...
J.J. Beam
  • 2,612
  • 2
  • 26
  • 55
  • 1
    That's an opinionated question. It depends. For instance, we don't know what are the contents of the employee, whether it's good to go to be translated into JSON as is, or you're performing some serialization tweaks via data-binding annotations (mixing them with JPA annotation might not look very nicely), but we don't know whether you're concerned about such things. There's no clear **right** or **wrong** here. – Alexander Ivanchenko Oct 12 '22 at 16:17
  • It also depends..on who can "access" this "end point" ...i heard of a "fashion" not to return any "internal information" to the client! (Including/especially "internal id"..so according to this ["fashion"](https://softwareengineering.stackexchange.com/q/218306/41957), you would "obfuscate"/return "public/individual IDs". https://github.com/patrickfav/id-mask – xerx593 Oct 12 '22 at 16:36
  • 2
    "Tight coupling" vs "(don't) repeat yourself".. (also) conflicting !(?) – xerx593 Oct 12 '22 at 16:39

2 Answers2

4

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.

bharathp
  • 355
  • 1
  • 5
  • 16
0

Yes, by coupling the entity directly to the controller it causes something we call tight coupling. Most of the time you want to achieve the opposite (loose coupling) the DTO pattern helps with this. The bad thing about tight coupling is that it essentially causes changes in a class while changing another class.

For more information about coupling check the answers on this question.

KurUkur
  • 23
  • 5