JTA with PersistenceUnit

Can it be @PersistenceUnit

used with JTA in JPA? If so, how is this possible?

Per http://tomee.apache.org/jpa-concepts.html :

Since <persistence-unit transaction-type="RESOURCE_LOCAL">

[...]

  • You have to use EntityManagerFactory to get EntityManager
  • [...]
  • EntityManagerFactory can only be injected using @PersistenceUnit annotation (not @PersistenceContext)

Since <persistence-unit transaction-type="JTA">

[...]

  • EntityManager can only be injected using @PersistenceContext annotation (not @PersistenceUnit)

I have similar code that uses JTA and @PersistenceUnit

. But sometimes I get NullPointerException

when I attach a transaction (defined as @Resource

).

+3


source to share


2 answers


Using JTA means that you are delegating work to the container. You can override it using UserTransaction

. Your quote contains all the answers you want to know. Using PersistenceUnit

to receive EntityManager

will not work.

If you use RESOURCE_LOCAL

, you are responsible for the transaction using EntityManager.getTransaction()

. An entity administrator is created EntityManagerFactory

. To get this factory you can use PersistenceUnit

.

So the simple answer is no if you rely on ship-driven containers.



See http://docs.oracle.com/javaee/6/tutorial/doc/bnbqw.html for an example

Application managed managers = RESOURCE_LOCAL

can use UserTransaction

(which are part of JTA).

0


source


What does object manager mean ??? If I'm a naive programmer, I can just interpret something that drives an entity, and in fact it means the same thing.

enter image description here

The Entity Manager content was created using the Factory Entity Manager. The database connection is managed by the entity manager, that is, it provides the functionality to perform operations on the database. Therefore, we could say that if the application requires multiple database connections, the EntityManagerFactory will be created for a specific database, which provides an efficient way to create multiple EntityManager instances (if required, even one instance of the Object Manager can work depending on the requirement that you can choose multiple instances) for this database needed for each HTTP request. We'll understand this with an example. Suppose we have Database: A, which has relational tables B and C. Thus, for A, an instance of the factory object manager will be created.Now, whenever we want to perform some kind of update on table B and allow delete operation on table C, either two different entity managers can be instantiated, or the same entity manager instance can be used for both. Implementing the Entity Manager factory itself is considered less efficient, but since it is a one-time activity, so it is a manageable task, since the Entity Manager factory, once instantiated, will serve the entire application. The entity created by the administrator is associated with a persistence context.Implementing the Entity Manager factory itself is considered less efficient, but since it is a one-time activity, so it is a manageable task, since the Entity Manager factory, once instantiated, will serve the entire application. The entity created by the administrator is associated with a persistence context.Implementing the Entity Manager factory itself is considered less efficient, but since it is a one-time activity, so it is a manageable task, since the Entity Manager factory, once instantiated, will serve the entire application. The entity created by the administrator is associated with a persistence context.

@PersistenceUnit(unitName = "MyDatabase")
EntityManagerFactory emf;
EntityManager entityManager = emf.createEntityManager();

      

or

@PersistenceContext(unitName = "MyDatabase") 
private EntityManager entityManager;

      

PersistenceUnit injects EntityManagerFactory and PersistenceContext injects EntityManager. It is generally best to use PersistenceContext unless you really need to manually manage the EntityManager lifecycle. EntityManagerFactory defines another method for creating EntityManager, which, like a factory, takes a property map as an argument. This form is useful when you need to provide a username and password other than the default EntityManagerFactory username and password:

Map properties = new HashMap(); 
properties.put("javax.persistence.jdbc.user", "kashyap");
properties.put("javax.persistence.jdbc.password","kashyap"); 
EntityManager em = emf.createEntityManager(properties);

      

In the context of persistence, entity instances and their life cycle are managed. By Entity instance we mean an entity instance and each entity designates a relational table in the database. The Entity Manager is actually an interface that provides methods for creating and deleting persistent instances of entities, searching for entities by their primary key, and querying by entity, so these functions are grouped under the operations we perform. Operations that modify the contents of the database require active transactions. Transactions are managed by the entity transaction instance obtained from the EntityManager. Precise definition: - The entity manager is defined by the unit of conservation. The persistence unit defines the set of all classes that are related or grouped by the application,and which should be placed in their mapping in one database. Below I am writing a piece of code for better understanding: -

try {
        em.getTransaction().begin();
        // Operations that modify the database should come here.
        em.getTransaction
        /**
        *getTransaction() EntityManager method Return the resource-level EntityTransaction object. See JavaDoc Reference Page
        */
        em.getTransaction().commit();
  }
  finally {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
  }

      



Continues to operate in accordance with JPA specification: - 1) Extended vs Transactional - Scoped: The default is Transactional Persistence Context, which means that all changes are cleared and all managed objects are no longer parsed when the current transaction is committed. The extended scope is only available to Stateful EJBs, and it even makes perfect sense since stateful beans can persist state, so it can be said that the end of one business method does not necessarily mean the end of a transaction. With Stateless beans, it has a different aspect. We have a business method that needs to end when the business method ends. ===> One method = one transaction; For stateless Beans, only entity manager with transactional scope is allowed You can control,if the EntityManager is extended or transactional during EntityManager Injection: -

@PersistenceContext (type = javax.persistence.PersistenceContextType.EXTENDED)
    EntityManager emng;

      

The default is javax.persistence.PersistenceContextType.TRANSACTION PersistenceContext extended and transactional values ​​are only allowed in the case of container-managed EntityManager. Time to speed up a bit: Container-managed vs. Application Control 2) Container-managed vs. Application Control:

@PersistenceContext
EntityManager emng;

      

The above statement allows the Container to inject an object manager for you, hence container-managed. Alternatively, you can create the EntityManager yourself using the EntityManagerFactory. But this time the injection will be a bit bit -

@PersistenceUnit
EntityManagerFactory emf;

      

Now, to get the EntityManager you need to call

emf.createEntityManager();

      

And there you go - you are using an application driven persistence context. You are now in charge of creating and deleting the EntityManager. Focus before reading the next couple, because what a confusing context I'm trying to solve, you can use createEntityManager if you want to have control over the generated EM - for example. if you need to move the created EntityManager across multiple beans participating in the trasaction - the container will not do that for you and every time you call createEntityManager () you create an EntityManager that is associated with the new PersistenceContext. You can use CDI sharing for EntityManager. Stay tuned for Entity Transaction - JPA and Resource-local will post a detailed discussion. Hope this gives a quick insight into the context. and feel free to post requests.

Read the second part from here

0


source







All Articles