Skip to content

DAO

We configure our DAOs with annotations so that Spring Boot will manage them and their dependencies.

  1. Mark the Impl class as javax.transaction.Transactional to have Spring automatically start a transaction for each DAO method and commit the transaction at the end of the method.

@Transactional
public class ActorDAOImpl implements ActorDAO {
  // ...
}
* An unchecked (runtime) exception will trigger a rollback.

  1. Also above the class definition, add the @Service annotation.

  2. Adding @Service will allow Spring Boot to create the DAO bean (found through component scanning) and inject it into the Controller using @Autowired.

@Transactional
@Service
public class ActorDAOImpl implements ActorDAO {
  // ...
}
  1. Inject an EntityManager into a field using the @PersistenceContext annotation.
@Transactional
@Service
public class ActorDAOImpl implements ActorDAO {

  @PersistenceContext
  private EntityManager em;
  // ...
}
  • You can now use this em field in your DAO methods to call find(), persist(), etc.

  • This is a container-managed EntityManager, so you should NEVER call close() on it.

Drill

  1. In com.example.bootmvc.data create an interface called FilmDAO that exposes a single method: Film findById(int id);.

  2. Next create a class that implements the interface called FilmDAOJpaImpl.

  3. Follow the steps listed above to configure the DAO implementation.

    • Instead of retrieving the EntityManager from the Persistence, declare an EntityManager as a field and annotate it with @PersistenceContext
  4. Be sure to mark your FilmDAOJpaImpl with both @Transactional and @Service.
  5. Add code into findById to retrieve a Film using the EntityManager find method.

Prev -- Up -- Next