2.3.  Write code to implement the DAO Pattern

[Note]

A data access object (DAO) is an object that provides an abstract interface to some type of database or persistence mechanism, providing some specific operations without exposing details of the database. It provides a mapping from application calls to the persistence layer. This isolation separates the concerns of what data accesses the application needs, in terms of domain-specific objects and data types (the public interface of the DAO), and how these needs can be satisfied with a specific DBMS, database schema, etc. (the implementation of the DAO).

The advantage of using data access objects is the relatively simple and rigorous separation between two important parts of an application that can and should know almost nothing of each other, and which can be expected to evolve frequently and independently. Changing business logic can rely on the same DAO interface, while changes to persistence logic does not affect DAO clients as long as the interface remains correctly implemented.

The CustomerDAO interface shown below defines the DAO methods for Customer persistent object that are implemented by all concrete DAO implementations, such as DerbyCustomerDAO, OracleCustomerDAO, and DB2CustomerDAO.


import java.util.Collection;

public interface CustomerDAO {
    public int insertCustomer(Customer c);
    public boolean deleteCustomer(Customer c);
    public Customer findCustomer(int id);
    public boolean updateCustomer(Customer c);
    public Collection<Customer> selectCustomers(String query);
}

					

The DerbyCustomerDAO implements the CustomerDAO as shown in code below:


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;

public class DerbyCustomerDAO implements CustomerDAO {

    Connection con;
    ResultSet rs;
    Statement stmt;

    public DerbyCustomerDAO() throws SQLException {
        con = getConnection();
    }

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:derby:sample;user=mikalai;password=pswd");
    }

    @Override
    public int insertCustomer(Customer c) {
        // ...
    }

    @Override
    public boolean deleteCustomer(Customer c) {
        // ...
    }

    @Override
    public Customer findCustomer(int id) {
        // ...
    }

    @Override
    public boolean updateCustomer(Customer c) {
        // ...
    }

    @Override
    public Collection<Customer> selectCustomers(String query) {
        // ...
    }
}

					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide