DAO Design Pattern
DAO Design Pattern
With DAO design pattern, we have following components on which our design
depends:
With above mentioned components, let’s try to implement the DAO pattern.
We will use 3 components here:
1. The Book model which is transferred from one layer to the other.
2. The BookDao interface that provides a flexible design and API to implement.
3. BookDaoImpl concrete class that is an implementation of the BookDao interface.
public Books() {
}
Let’s define the interface to access the data associated with it at persistence
level.
import java.util.List;
List<Books> getAllBooks();
Books getBookByIsbn(int isbn);
void saveBook(Books book);
void deleteBook(Books book);
}
import java.util.ArrayList;
import java.util.List;
public class BookDaoImpl implements BookDao {
public BookDaoImpl() {
books = new ArrayList<>();
books.add(new Books(1, "Java"));
books.add(new Books(2, "Python"));
books.add(new Books(3, "Android"));
}
@Override
public List<Books> getAllBooks() {
return books;
}
@Override
public Books getBookByIsbn(int isbn) {
return books.get(isbn);
}
@Override
public void saveBook(Books book) {
books.add(book);
}
@Override
public void deleteBook(Books book) {
books.remove(book);
}
}
//update student
Books book = bookDao.getAllBooks().get(1);
book.setBookName("Algorithms");
bookDao.saveBook(book);
}
}
There are many advantages for using DAO pattern. Let’s state some of them
here: