Tuesday, December 31, 2013

My goal is to have a standalone solution for building JUnit tests for local and distributed transactions using JPA over Hibernate over MySQL.
So far, I have been able to use an XADataSource to access a XAResource and manage the distributed transaction following the 2 phase commit protocol. However, I have to issue SQL statements directly.
I have been trying to do the same but using JPA 2.0 persistence. I'm using simple-jndi to have an in-memory JNDI implementation.
However I keep getting NullPointerException whenever Hibernate tries to access the TransactionManager.
Any ideas? What is missing from my configuration?
Here's what I would like to do:
    // Create the XA datasource instance directly
    MysqlXADataSource mysqlDS = new MysqlXADataSource();

    // setup local JNDI
    final XADataSource xaDataSource = (XADataSource) mysqlDS;

    InitialContext ctx = new InitialContext(  );
    ctx.bind("java:/ExampleDS", xaDataSource);

        Object o = ctx.lookup("java:/ExampleDS");
        System.out.println("Test lookup: " + o);

    // XID - transaction ID

    // global transaction identifier
    // -      --          --
    byte[] gtrid = new byte[] { 0x44, 0x11, 0x55, 0x66 };

    // branch qualifier
    // -      ----
    byte[] bqual = new byte[] { 0x00, 0x22, 0x00 };

    // combination of gtrid and bqual must be unique

    Xid xid1 = new com.mysql.jdbc.jdbc2.optional.MysqlXid(gtrid, bqual, 0);
        // byte[] gtrid, byte[] bqual, int formatId

    // before transaction
        XADataSource xaDS = (XADataSource) ctx.lookup("java:/ExampleDS");

        XAConnection xaconn = xaDS.getXAConnection();
        Connection conn = xaconn.getConnection();
        XAResource xares = xaconn.getXAResource();

        /* the transaction begins */
        System.out.println("Start transaction");
        xares.start(xid1, TMNOFLAGS);

    // JPA code

    EntityManagerFactory emf;
    emf = Persistence.createEntityManagerFactory("MyPersistenceUnit"); // defined in persistence.xml
    EntityManager em = emf.createEntityManager();

    // System.out.println("begin");
    // em.getTransaction().begin();

    System.out.println("new ContactBook");
    ContactBook contactBook = new ContactBook("Alice");

    contactBook.addContact("Alice", 100100100);
    contactBook.addContact("Bob", 200200200);
    contactBook.addContact("Charlie", 300300300);


    // System.out.println("commit");
    // em.getTransaction().commit();

    // after transaction
        XADataSource xaDS = (XADataSource) ctx.lookup("java:/ExampleDS");
        System.out.println("xaDS " + xaDS);

        XAConnection xaconn = xaDS.getXAConnection();
        Connection conn = xaconn.getConnection();
        XAResource xares = xaconn.getXAResource();

        System.out.println("End transaction");
        xares.end(xid1, TMSUCCESS);

        // prepare, commit

        System.out.print("Prepare... ");
        int rc1 = xares.prepare(xid1);

        if (rc1 == XA_OK) {
            xares.commit(xid1, /*onePhase*/ false);
        } else if(rc1 == XA_RDONLY) {
            System.out.println("Commit no necessary - operations were read only");
        } else {
            throw new IllegalStateException("Unexpected case!");
Here is persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
<persistence-unit name="ContactBookPersistenceUnit" transaction-type="JTA">
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
        <property name="hibernate.show_sql" value="true" />

        <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup"/>

        <property name="current_session_context_class" value="jta"/>

        <property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory"/>
        <property name="hibernate.connection.release_mode" value="auto"/>


share|improve this question
add comment
I believe you cannot use JTA transactions when you are outside a Java EE container (or at least there is no easy way to do this).
There is nothing that requires JTA in your example: you are just looking up a data source in a Java SE environment. I think declaring your XA data source as resource-local would solve your problem. Put this in your persistence.xml:
<persistence-unit name="ContactBookPersistenceUnit" transaction-type="RESOURCE-LOCAL">
I have not tested this code directly, but I have used a similar approach in web applications written for the Apache Tomcat server.
Use an embedded container
Another option you may investigate involves starting an embedded Java EE container in you JUnit tests. Here are a couple of pointers, with examples for Glassfish 3:
share|improve this answer


oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes