DEV Community

Using the Data Mapper Pattern in a Simple Customer Management System

In big applications, it's important to keep the business logic (how the app works) separate from the data logic (how the app talks to the database). One way to do this is by using the Data Mapper Pattern. This pattern helps transfer data between the app’s objects and the database without making them depend on each other.

Example: Customer Management System
Let's say we are building a system to manage customers, where we need to store and retrieve customer information from a MySQL database.

  1. Customer Class (Domain) This class holds the customer’s information and business logic.
public class Customer {
    private int id;
    private String name;
    private String email;
    // Getters and setters
}

Enter fullscreen mode Exit fullscreen mode
  1. CustomerMapper Interface This defines methods to interact with the database.
public interface CustomerMapper {
    Customer findById(int id);
    void insert(Customer customer);
    void update(Customer customer);
    void delete(int id);
}

Enter fullscreen mode Exit fullscreen mode
  1. CustomerMapperImpl Class This class uses JDBC to handle the actual database operations.
import java.sql.*;

public class CustomerMapperImpl implements CustomerMapper {
    private Connection connection;

    public CustomerMapperImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Customer findById(int id) {
        // Code to get a customer from the database
    }

    @Override
    public void insert(Customer customer) {
        // Code to add a customer to the database
    }

    @Override
    public void update(Customer customer) {
        // Code to update a customer in the database
    }

    @Override
    public void delete(int id) {
        // Code to delete a customer from the database
    }
}

Enter fullscreen mode Exit fullscreen mode

Benefits

  • Separation of Concerns: The app's business logic is separate from database logic.
  • Flexibility: You can change the database without changing the business logic code.

Top comments (0)