Is it right to write DB Operations in a POJO or DTO Class?

Viewed 35

Let's say we have a Class Customer

Class Customer
{
    String name, emailId;

    public void setName(String name)
    {
       this.name = name;
    }
    public String getName()
    {
       return this.name;
    }
  
    //Getter and Setter for Email ID

    public void addNewCustomer()
    {
        //DB Operations
    } 
}

Now I have to persist a new row to the Database table Customer.

Do I add a method addNewCustomer as above and access it as below ?

Customer customer = new Customer();
customer.addNewCustomer();

Or

I should have a separate Class say,

Class CustomerUtil
{
     public static void addNewCustomer(Customer customer)
     {
        //DB Operations
     }
}

Is there any standards that we could follow here ?

2 Answers

Actually DB operations are part of Data Access Objects(DAO) class. Any read or write operation should be done in DAO class. The POJO or DTO should not be used, it is meant for Business or Service Data Transfers. In DAO class there should be "Entity" objects which should be replica of your tables. In the read and write operations Entity Objects should be used.

It depends on what architecture is used in application.

If you have layered architecture:

  • Service layer should have business logic
  • Data layer is responsible for CRUD operation and this layer should be very simple. This layer should not have any logic, except base CRUD logic. Model classes should not have any logic as ORM prevents you from having logic in model classes.
  • UI layer should be responsible only for presentation and deal with DTOs or ViewModels

Read more about other architectures here in this beautiful answer

Related