Showing posts with label dao / data access object. Show all posts
Showing posts with label dao / data access object. Show all posts

Wednesday, 22 June 2011

Data Access Object ( DAO ) Pattern

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.

A typical DAO implementation has the following components:
  • A DAO interface
  • A concrete class that implements the DAO interface
  • Entities OR Data transfer objects (sometimes called value objects)
Seeing all the components with the Example

Entity

Order.java
public class Order{
private int id;
private String customerName;
private Date date;

public int getId() { return id; }
public void setId(int id) { this.id = id; }

public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) {  
          this.customerName = customerName;  
    }

public Date getDate() { return date; }
public void setDate(Date date) { this.date = date;}
}

DAO interface
OrderDao.java
Get the interface for Create Retrieve Update and Delete operations.

//holds all CRUD behaviours
public interface OrderDao {
void create(Order entity);
Order findById(int id) throws OrderDontExistException;
void update(Order entity);
void delete(Order entity);
}

DAO Implementation
OrderDaoImpl.java
This just takes the datasource object and stores all the queries related to Order object. I am just implementing finById method for simplicity.

public abstract class OrderDaoImpl implements OrderDao {

DataSource ds;
public OrderDaoImpl(DataSource ds_) {
ds = ds_;

}

public void create(Order entity) { //do something }

public E findById(int id) throws OrderDontExistException {
String sqlFindById = "select * from ORDERS where id=?";
Connection con = getConnectionFromDataSource(ds);
PreparedStatement ps= con.prepareStatement(sqlFindById);;
ps.setInt(1, id);
ResultSet rs = ps.execute();
//process result set
Order order = rs.getString("Name");
//... so on

return order;
}

public void update(Order entity) { //do something }

public void delete(Order entity) { //do something }

}

Exception class

package authordao;



public class OrderDontExistException extends Exception {


public OrderDontExistException() {

// TODO Auto-generated constructor stub

}


public OrderDontExistException(String message) {

super(message);

// TODO Auto-generated constructor stub

}


public OrderDontExistException(Throwable cause) {

super(cause);

// TODO Auto-generated constructor stub

}


public DAOException(String message, Throwable cause) {

super(message, cause);

// TODO Auto-generated constructor stub

}


}
Using the Dao

OrderDao dao = new OrderDaoImpl(ds);
Order order = dao.findById(id);
//Now do some business logic

Conclusion
As this article has shown, implementing the DAO pattern entails more than just writing low-level data access code. You can start building better DAOs today by choosing a transaction demarcation strategy that is appropriate for your application, by incorporating logging in your DAO classes, and by following a few simple guidelines for exception handling.

Tuesday, 14 June 2011

Repositories vs DAOs

"Are Repository and DAOs the same thing with a different name?". The answer is not direct. Because they overlap a lot. Repositories and DAOs are two solution styles for approaching the same problem, with some small differences.
  1. DAOs are strictly tied to the underlying representation on a DBMS. The original specification is more generic, allowing for file-based persistence and the like. But the vast majority of DAOs are pointing to a DBMS. Moreover, commonly used persistence frameworks, such as Hibernate help a lot in managing database portability, so this is a smaller issue nowadays, than it used to be. As a result the DAO concept eventually downsized, to a "database access point" while Repositories are still intended to be generic.
  2. Repositories provide a more abstract view over the underlying data model, providing an interface strictly coherent with the domain. DAOs might be implemented basically in many ways, but frameworks and code generation tools tend to put the focus on the data structure rather than on the domain model. This is sometimes a tiny issue, sometimes just a matter of style, but in large systems can degenerate in a severe maintenance problem.
  3. Repositories enforce access to the persistence layer on a one-repository-per-aggregate basis, while DAOs are normally developed one-per-entity or one-per-table. So, repositories are more tied to the DDD concept of Aggregate Root and have a different granularity than DAOs. This definitely makes the most significant difference.
Somehow, the differences above are just a matter of taste, except for point 3. So objections are valid and discussion may result endless. But for now I'll just say that the two patterns are doing basically the same thing, although with different styles. There are differences, especially if approaching the matter from a DDD angle. What's left to say is if those differences are enough to make a choice between one pattern and another, or eventually to choose both.