DAO
We configure our DAOs with annotations so that Spring Boot will manage them and their dependencies.
- Mark the Impl class as
javax.transaction.Transactionalto 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 {
// ...
}
-
Also above the class definition, add the
@Serviceannotation. -
Adding
@Servicewill 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 {
// ...
}
- Inject an EntityManager into a field using the
@PersistenceContextannotation.
@Transactional
@Service
public class ActorDAOImpl implements ActorDAO {
@PersistenceContext
private EntityManager em;
// ...
}
-
You can now use this
emfield in your DAO methods to callfind(),persist(), etc. -
This is a container-managed EntityManager, so you should NEVER call
close()on it.
Drill¶
In com.example.bootmvc.data create an interface called FilmDAO that exposes a single method:
Film findById(int id);.Next create a class that implements the interface called FilmDAOJpaImpl.
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- Be sure to mark your FilmDAOJpaImpl with both
@Transactionaland@Service.- Add code into
findByIdto retrieve a Film using the EntityManagerfindmethod.