Enterprise Java Development@TOPIC@

Chapter 33. DAO Interface

33.1. DAO Interface
33.2. DAO Exceptions
33.3. DAO Implementation
33.4. DAO Test
...

import javax.persistence.PersistenceException;
public interface BookDAO {
    Book create(Book book) throws PersistenceException;
    Book update(Book book) throws PersistenceException;
    Book get(long id) throws PersistenceException;
    void remove(Book book) throws PersistenceException;
    List<Book> findAll(int start, int count) throws PersistenceException;
}

Adds implementation out-of-band from DAO interface

...

public class JPABookDAOImpl implements BookDAO {
    private EntityManager em;    
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }
    @Override
    public Book create(Book book) { ... }
    
    @Override
    public Book update(Book book) { ... }
    @Override
    public Book get(long id) { ... }
    @Override
    public void remove(Book book) { ... }
    @Override
    public List<Book> findAll(int offset, int limit) { ... }
}

Demonstrates how technology-neutral DAO clients can be when dao implementation is injected into client.

...

public class BookDAOTestBase {
    protected BookDAO dao; //sub-classes will provide an implementation.
    protected Book makeBook() {
        Random random = new Random();
        Book book = new Book();
        book.setTitle("GWW-" + random.nextInt());
        ...
        return book;
    }
    @Test
    public void testCreate() {
        Book book = makeBook();
        assertEquals("id not assigned", 0, book.getId());
        book = dao.create(book);
        assertTrue("id not assigned", book.getId()>0);
    }
    
    @Test
    public void testGet() {... }    
    @Test
    public void testUpdate() { ... }    
    @Test
    public void testDelete() { ... }
    @Test
    public void testFindAll() { ... }
}