1 Reply Latest reply: Dec 19, 2011 11:31 AM by Michael Musgrove RSS

Distributed transaction

Amar Das Newbie

All:

 

Does anyone have an example of connecting to two databases using JPA (2 persistence.xml) and performing a XA transaction?

 

Thanks

  • 1. Re: Distributed transaction
    Michael Musgrove Master

    I don't have a ready made example but to get you started you will need something along the following lines:

     

            <persistence-unit name="pctx1">

                    <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>

                    <properties>

                      <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver" />

                      <property name="hibernate.connection.url" value="jdbc:h2:mem:test1" />

                      <property name="hibernate.connection.username" value="sa" />

                      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />

                      <property name="hibernate.hbm2ddl.auto" value="create" />

                      ....

                    </properties>

            </persistence-unit>

            <persistence-unit name="pctx2">

                    <jta-data-source>java:jboss/datasources/ExampleDS2</jta-data-source>

                    <properties>

                    ... etc

     

    in your persistence.xml where you have configured java:jboss/datasources/ExampleDS and java:jboss/datasources/ExampleDS2 as xa datasources in your XML config

     

    followed by

     

    public class XAService {

       @PersistenceContext(unitName = "pctx1")

       EntityManager em1;

       @PersistenceContext(unitName = "pctx2")

       EntityManager em2;

     

       public void doXA() {

          UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");

          ut.begin();

          em1.persist(new Entity1("E1"));

          em2.persist(new Entity2("E2"));

          ut.commit();

       }