Home > Net >  When to use Entity and when DTO?
When to use Entity and when DTO?

Time:01-24

So I'm working with Apache beam with SpringBoot, and with JDBCIO in .query I'm retrieving records from table "customer" (select * from records.customer where customer_code = "abc").So this "customer" class should be an entity or a DTO ?

My understanding is we need an entity only when we are working with repositories. Correct me if I'm wrong.

CodePudding user response:

You could use either one of them depending on your domain. Entities are used to go with your domain scope. It applies "behavior". DTO(Data Transfer Object) are used to transfer data from one process/module to a another.

CodePudding user response:

You would use an Entity while dealing with a JPA Repository. The thing to keep in mind is that an Entity is basically a representation of your Database and thus, for example with Hibernate (a JPA implementation), every change you in an Entity data will be at some point persisted in the database. This might be exactly what you need and want or maybe it is not and you must be cautious. Imagine that you share Entities between two different Service classes and one of them make changes to it, effectively having side-effects. This is usually a source of bugs.

A DTO (Data Transfer Object) is usually used to expose your Entities via a REST API. If you would use Entity itself, you might get in trouble when Jackson tries to serialize the object to JSON. You might as well see code that actually uses DTOs to communicated between Services. This usually reduces the possibility of bugs (as described earlier) but it also makes your code more complex and might make it hard to achieve some use cases.

  •  Tags:  
  • Related