Home > Software engineering >  DTO, DAO and Entity ? Is Entity needed ? Best pratice with those 3?
DTO, DAO and Entity ? Is Entity needed ? Best pratice with those 3?

Time:11-05

I assume if you're using DTO and DAO, there is no need for entities, at least examples that i saw in this way. Or is it optional to have entities in this scenario ?

public interface CustomerResource {

    @GET
    @Path("/getCustomerListByUserID/{userID}")
    Response getCustomerListByUserID(@PathParam("userID") String userID);

    @DELETE
    @Path("/deleteCustomer/{customerID}")
    Response deleteCustomer(@PathParam("customerID") int customerID);

    @POST
    @Path("/updateCustomer")
    Response updateCustomer(CustomerDTO customer);
 }


public class CustomerResourceImpl implements CustomerResource{

 @Override
 public Response deleteCustomer(int customerID) {
     internalService.deleteCustomer(customerID);
 }

 @Override
 public Response getCustomerListByUserID(String userID) {
     internalService.getCustomerListByUserID(customerID);
 }

 @Override
 public Response updateCustomer(CustomerDTO customer) {
     internalService.updateCustomer(customer);
 }
}

public interface CustomerDAO extends BaseDAO<CustomerDTO> {
 
     List<CustomerDTO> getCustomerListByUserID(String userID);
 
     void deleteCustomer(Integer customerID);
 
     void updateCustomer(CustomerDTO customer);
 }

And internalService directly calls CustomerDAO

Are there anything wrong about this structure, how can it be better, is there any need for Customer entity?

Thank you so much ! Wish success for you all !

CodePudding user response:

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

DTO should only contain private fields for your data, getters, setters, and constructors. DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods. DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
protected String name;
...getter and setter
}

An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table.

  • Related