NOTE:
This page is a child of JPA page.
EntityManager
In the AffableBean project, all of the EJBs employ the EntityManager. Any of the session facade beans uses the @PersistenceContext annotation to express a dependency on a container-managed EntityManager and its associated persistence context (AffableBeanPU, as specified in the persistence.xml file).For example, the ProductFacade bean looks as follows [1]:
@Stateless public class ProductFacade extends AbstractFacade<Product> { @PersistenceContext(unitName = "AffableBeanPU") private EntityManager em; protected EntityManager getEntityManager() { return em; } ... // manually created public List<Product> findForCategory(Category category) { return em.createQuery("SELECT p FROM Product p WHERE p.category = :category"). setParameter("category", category).getResultList(); } }
Use the EntityManager to mark entity objects to be written to the database
em.persist(customer);
NOTE:
[1]The EntityManager's persist method does not immediately write the targeted object to the database. To describe this more accurately, the persist method places the object in the persistence context. This means that the EntityManager takes on the responsibility of ensuring that the entity object is synchronized with the database. Think of the persistence context as an intermediate state used by the EntityManager to pass entities between the object realm and the relational realm (hence the term 'object-relational mapping').
What is the scope of the persistence context? If you examine the Javadoc documentation for the @PersistenceContext annotation, you'll note that the type element is used to specify one of the above:
- A transaction-scoped persistence context (default behavior): is created at the start of a transaction, and terminated when the transaction ends.
- An extended persistence context: applies to stateful session beans only, and spans multiple transactions.
References:
[1] - The NetBeans E-commerce Tutorial - Integrating Transactional Business Logic
Sem comentários:
Enviar um comentário