ObjectDB ObjectDB

Step 3: Define a Spring DAO Component

Operations on the database will be performed by an instance of a Data Access Object (DAO) that we will define in this step as a Spring MVC component:

  • Open the [New Java Class] dialog box by right clicking the guest package node (in the [Projects] window under Source Packages) and selecting New > Java Class....
  • Enter GuestDao as the class name - use exactly that case sensitive class name.
  • The Package should be guest.
  • Click Finish to create the new DAO Spring component class.

Now replace the content of the new source file with the following code:

package guest;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

public class GuestDao {
    // Injected database connection:
    @PersistenceContext private EntityManager em;

    // Stores a new guest:
    public void persist(Guest guest) {

    // Retrieves all the guests:
    public List<Guest> getAllGuests() {
        TypedQuery<Guest> query = em.createQuery(
            "SELECT g FROM Guest g ORDER BY g.id", Guest.class);
        return query.getResultList();

The GuestDao Spring component class defines two methods:

  • persist - for storing a new Guest entity object in the database.
  • getAllGuests - for retrieving all the existing Guest objects from the database.

By using Spring components we can move some work from the application to the Spring Framework. For instance, in this example the Spring container:

  • Manages the instantiation of the DAO component class and injects an instance of the DAO component class into the controller, as shown in the next step.
  • Prepares an EntityManager automatically and injects it into the em field (because it is annotated with the @PersistenceContext annotation).
  • Handles transactions automatically for methods that are annotated with the @Transactional annotation, saving the need to wrap every operation that modifies the database (such as persist) by transaction begin and commit.

The next step is adding a Controller Class.