Trouble enlisting direct JDBC in a transaction
bobsmith Sep 23, 2005 12:03 PMHello,
I am getting a ClassCastException when doing the following:
XADataSource m_XADataSource = (XADataSource) ctx.lookup("java:/MyDataSource");
My problem is no doubt not just the above line but my whole understanding of the area of Transactions.
I am replacing the entity beans in our application with JDBC and I am considering the following situation:
SessionBean1.method1 {Transaction="RequiresNew"}
create entity (CMP)
SessionBean2.method2 {Transaction="Supports"}
I think I'm right in saying that if SessionBean2.method2 throws a system exception then SessionBean1.method1 will rollback and the entity I created will not be comitted to the database.
If I replace the entity creation with JDBC code, then my thinking is that, unless I do something clever, the entity will be comitted to the database even if SessionBean2.method2 throws a system exception. So my plan of attack was to, in my JDBC code, check if there is a current transaction and, if there is, join in.
So, am I barking up the wrong tree completely, or is this a sensible approach? [please don't refer to Hibernate, Spring JDBC, or any other framework - I need to know if it is an OK approach for JDBC].
The code I have put in to achive my goal is as follows, but I get no further than the line marked "***** FAILS HERE" - the first line!! :
XADataSource m_XADataSource = (XADataSource) ctx.lookup("java:/MyDataSource"); *****FAILS HERE with ClassCastException TransactionManager txManager = (TransactionManager)context.lookup("java:/TransactionManager"); Transaction tx = txManager.getTransaction(); XAConnection connection = m_XADataSource.getXAConnection(); if (tx != null) { XAResource xares = connection.getXAResource(); tx.enlistResource(xares); } PreparedStatement ps = connection.getConnection().prepareStatement("some sql");
The mysql-ds.xml file I am using is:
<datasources> <local-tx-datasource> <jndi-name>MyDataSource</jndi-name> <connection-url>jdbc:mysql://localhost:3306/testdb</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>theuser</user-name> <password>thepassword</password> <prepared-statement-cache-size>50</prepared-statement-cache-size> </local-tx-datasource> </datasources>
and I'm using versions 3.2.6 of JBoss and 3.1.6 of MySQL Connector-J.
Many thanks,
Paul