CRUD operations in Data Access Object (DAO)

CRUD stands for create, read, update, and delete. It refers to the common tasks you want to carry out on a database. Data access object (DAO) is a design pattern that follows high cohesion (and single responsibilty) principle and is used to abstract away data persistence operations from the rest of the application. You can read further about it here.

Quote from Wikipedia

The primary advantage of using data access objects is the relatively simple and rigorous separation between two important parts of an application that can but should not know anything 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 do not affect DAO clients as long as the interface remains correctly implemented.

Let's implement the CRUD operations using the DAO design pattern. Make a DAO interface (add it under a new package named persistence):

package persistence;
import exception.DaoException;
import model.Book;
import java.util.List;
public interface AuthorDao {
int add(Author book) throws DaoException;
List<Author> listAll();
  • The DaoException is a Runtime Exception; implement it and place it in exception package.
  • We have limited the operations of AuthorDao to add and listAll for simplicity.

Likewise, we can implement a BookDao interface to be used for the book objects.