Enterprise Java Development@TOPIC@
Technology agnostic and business object-focused
No mention of Connection or EntityManager in methods
Ability to at least CRUD (with possible options)
Aggregate data functions added when behavior better performed at data source
Extensions added to address data access details for specific use cases (e.g., LAZY/EAGER load)
...
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;
}
The declaration of the unchecked/runtime exception PersistenceException is not required and is only being done here for extra clarity
Runtime Exceptions
Used to report unexpected issues (e.g., no connection)
Extends java.lang.RuntimeException
ex. javax.persistence.PersistenceException
Checked Exceptions
Used to report anticipated errors mostly having to do with input
Extends java.lang.Exception
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() { ... }
}