简体   繁体   中英

Two phase commit transaction in Java EE 5

I want to know that how can I do two phase commit transaction by using Java EE5...I am using EJB with JPA which has hibernate configured with MySql. I just want to use JAVA EE specification for transaction not using hibernate or JDBC specific object....

All you need to do, to ensure that JTA transactions are used to perform all transactional work in JPA, is to specify that the Persistence Unit type is JTA, and designate a JTA datasource for use by the JPA provider. Your persistence.xml file would have contents similar to the following:

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <!-- Specifies the type of the entity managers used by the persistence unit,
         as a JTA entity manager -->
    <persistence-unit name="example-pu" transaction-type="JTA">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <!-- Specifies a JTA datasource for use by the JPA provider.
             All connections obtained by the JPA provider for this persistence unit
             will be from this datasource -->
        <jta-data-source>jdbc/myDS</jta-data-source>
            ...
    </persistence-unit>
 </persistence>

Additionally, you must ensure that the datasource defined in the jta-data-source attribute, does not employ optimizations like allowing local transactions. In simpler words, all transactions involving the said datasource must be XA transactions, or the datasource must be an XA datasource without any support for local transactions.

Note that merely specifiying a JTA data source is not sufficient. You must define the persistence unit as one requiring the use of JTA entity managers, as an undefined value for the transaction-type attribute, depends on the environment in which the JPA provider operates. If the provider operates in a Java EE environment, JTA entity managers will be created, where as RESOURCE_LOCAL entity managers will be created in a Java SE environment.

Also, note that, if you specify the transaction-type as RESOURCE_LOCAL , then in a Java EE environment, the JPA provider will ignore the jta-data-source value, and will instead rely on the non-jta-data-source value for creating connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM