liveBook · Manning

Data access object

As explained in Java Persistence with Spring Data and Hibernate epub

The data access object pattern separates an abstract data-access interface from the implementation details of communicating with a database.

A data access object (DAO) gives application code an abstract interface for database operations. Callers request operations such as finding, inserting, updating, or deleting an entity without handling the details of database access. In a Spring JPA application, an interface declares those operations and a separate class implements them with JPA. section 14.2

Path: Ch14/spring-jpa-dao/src/main/java/com/manning/javapersistence/ch14
 /dao/ItemDao.java
 
public interface ItemDao {
    Item getById(long id);
 
    List<Item> getAll();
 
    void insert(Item item);
 
    void update(long id, String name);
 
    void delete(Item item);
 
    Item findByName(String name);
}

ItemDao makes the boundary concrete: it declares getById, getAll, insert, update, delete, and findByName without specifying how any operation reaches the database. section 14.2

A Spring-managed implementation can use an injected EntityManager to carry out that interface. @Repository identifies the DAO as a component and translates persistence-specific exceptions into Spring unchecked exceptions; @Transactional makes its methods transactional. Because an EntityManager is not itself thread-safe, @PersistenceContext supplies a container-managed proxy. In the shown configuration, EXTENDED keeps the persistence context for the bean's lifecycle. Transaction management and the required database infrastructure must also be configured. section 14.2

Listing 14.3 The ItemDaoImpl class
Path: Ch14/spring-jpa-dao/src/main/java/com/manning/javapersistence/ch14
 /dao/ItemDaoImpl.java
 
@Repository                                                             #1
@Transactional                                                          #1
public class ItemDaoImpl implements ItemDao {
    @PersistenceContext(type = PersistenceContextType.EXTENDED)         #2
    private EntityManager em;                                           #2
 
    @Override                                                           #3
    public Item getById(long id) {                                      #3
        return em.find(Item.class, id);                                 #3
    }
 
    @Override                                                           #4
    public List<Item> getAll() {                                        #4
        return (List<Item>) em.createQuery("from Item", Item.class)     #4
                              .getResultList();                         #4
    }
 
    @Override                                                           #5
    public void insert(Item item) {                                     #5
        em.persist(item);                                               #5
        for (Bid bid : item.getBids()) {                                #5
            em.persist(bid);                                            #5
        }                                                               #5
    }
 
    @Override                                                           #6
    public void update(long id, String name) {                          #6
        Item item = em.find(Item.class, id);                            #6
        item.setName(name);                                             #6
        em.persist(item);                                               #6
    }
 
    @Override                                                           #7
    public void delete(Item item) {                                     #7
        for (Bid bid : item.getBids()) {                                #7
            em.remove(bid);                                             #7
        }                                                               #7
        em.remove(item);                                                #7
    }
 
    @Override                                                           #8
    public Item findByName(String name) {                               #8
        return em.createQuery("from Item where name=:name", Item.class) #8
                .setParameter("name", name).getSingleResult();          #8
    }
}
#1 The <kbd>ItemDaoImpl</kbd> class is annotated with <kbd>@Repository</kbd> and <kbd>@Transactional</kbd>.
#2 The <kbd>EntityManager em</kbd> field is injected in the application, as annotated with <kbd>@PersistenceContext</kbd>. Persistence type <kbd>EXTENDED</kbd> means the persistence context is kept for the whole lifecycle of a bean.
#3 Retrieve an <kbd>Item</kbd> by its <kbd>id</kbd>.
#4 Retrieve all <kbd>Item</kbd> entities.
#5 Persist an <kbd>Item</kbd> and all its <kbd>Bid</kbd>s.
#6 Update the <kbd>name</kbd> field of an <kbd>Item</kbd>.
#7 Remove all the bids belonging to an <kbd>Item</kbd> and the <kbd>Item</kbd> itself.
#8 Search for an <kbd>Item</kbd> by its <kbd>name</kbd>.

ItemDaoImpl shows the interface implemented as a repository component, with transactional methods and an injected EntityManager; getById delegates to EntityManager.find. section 14.2

A handwritten DAO is not the only way to keep callers apart from persistence details. Spring Data JPA repositories provide the same kind of abstraction while generating the implementation, default CRUD methods, and queries derived from method names. Choose an explicit DAO when its implementation is useful to control; choose a repository when generated behavior avoids unnecessary boilerplate. Common DAO behavior can also be moved into a generic base class for either a Spring JPA or Spring Hibernate application. section 1.3 section 14.6

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Builds interfaces and implementations, then addresses injection, transactions, and reusable base classes rather than stopping at a pattern definition.
Examples
Uses ItemDao and BidDao interfaces, their Spring-managed implementations, and an application service that injects ItemDao.
What it assumes
Starts the DAO implementation with entity classes and teaches the access interfaces explicitly, while relying on Spring and JPA integration.
What you can do after
Build it from scratch with a Spring-managed JPA DAO, or evaluate whether a generated Spring Data JPA repository is sufficient.
How it connects
Connects dependency injection, JPA, Hibernate, EntityManager, transaction management, and Spring Data JPA repositories.

Also explained in

Compare how 2 books explain data access object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.