其他编程接口
在J2EE规范中,UserTransaction只能在Bean或者Servlet里面使用。那么在普通的POJO里面,如果访问事务,如果发起新的事务呢?WebSphere提供了下面的一些办法:
ExtendedJTATransaction
通过该接口可以知道当前有没有全局事务,如果有则可以注册一个SynchronizationCallback对象到当前的事务或者容器中所有的事务中。
可以在EJB、Servlet、JSP或者普通的POJO中通过下面的代码访问到该对象:
ExtendedJTATransactionexJTA = (ExtendedJTATransaction)ctx.lookup("
java:comp/websphere/ExtendedJTATransaction");
//判断是否有活动的事务
if (exJTA.getGlobalId() != null) {
//给当前的事务注册一个callback
SynchronizationCallback sync = new SynchronizationCallback();
exJTA.registerSynchronizationCallbackForCurrentTran(sync);}
ExtensionHelper
如果需要在POJO中发起新的事务,则可以用ExtensionHelper。示例代码如下:
InitialContext ctx = new InitialContext();
ExtensionHelper eh = (ExtensionHelper) ctx.lookcup(ExtensionHelper.JNDI_NAME);
TransactionControl tc = eh.getTransactionControl();
TxHandle txh = tc.preinvoke();
try {
// Do some work ...
// Commit the transaction
tc.postinvoke(txh);
} catch (Throwable fatalException) {
// Rollback the transaction
tc.handleException(txh);
}
UOWManager
在WAS6.1以后提供了一个更简洁的接口来实现对UOW的管理。上面在POJO中启动一个事务的代码可以重写如下:
try {
UOWManager uowManager = UOWManagerFactory.getUOWManager();
uowManager.runUnderUOW(UOWSynchronizationRegistry.UOW_TYPE_GLOBAL_TRANSACTION, false, new UOWAction()
{
public void run() throws Exception{
// Perform. transactional work here.
}
});
}catch (UOWActionException uowae)
{
// Transactional work resulted in a checked exception being thrown.
// The UOW was not affected.
}
catch (RuntimeException re) {
// Transactional work resulted in an unchecked exception being thrown.
// The UOW was rolled back
}
catch (UOWException uowe){
// The completion of the UOW failed unexpectedly.
}