GMsoF GMsoF - 2 months ago 15
Java Question

Use AutoCommit with UserTransaction together

Would like to know whether below is correct or not?

UserTransaction ut = getUserTransaction();
ut.begin();
conn = dataSource.getConnection();
conn.setAutoCommit(false);
stmt = conn.createStatement();
// perform statement query udpate here

// do i need to call conn.commit? or ut.commit will handle it implicitly?
ut.commit();


I saw the code snippet in one of my company's project, I tested it and found some weird behavior, so I am not sure, should we explicitly call
conn.commit()
? or leave the
ut.commit()
handle all the transaction inside itself?

So it started to confuse me what we are supposed to put inside the
UserTransaction.begin()
and
UserTransaction.commit()
? Since it should be mostly SQL statement execution code inside, is it necessary to include
conn = dataSource.getConnection();
inside the block as well? so all the
statement
that generated by the specific
connection
will behave implicitly like we use
AutoCommit(false)
? What happen if we declare the that (
conn = dataSource.getConnection()
) outside of block? Will transaction-handling still working?

Anyone please share some knowledge on how
UserTransaction
work? I basically know how to use it, but no concrete idea what should I take note when I am using it.

Answer

Enterprise beans that use container-managed transaction demarcation must not use any transaction-management methods that interfere with the container’s transaction demarcation boundaries. Examples of such methods are the commit, setAutoCommit, and rollback methods of java.sql.Connection or the commit and rollback methods of javax.jms.Session. If you require control over the transaction demarcation, you must use application-managed transaction demarcation.

Enterprise beans that use container-managed transaction demarcation also must not use the javax.transaction.UserTransaction interface.

I have read this , I think probably it is not very good idea to use Transaction and the autoCommit at the same time.