Introduction

Java Transaction API support is done using org.mybatis.guice.MyBatisJtaModule.

@Transactional support

Methods annotated with org.mybatis.guice.transactional.Transactional will be executed inside the JTA's active transaction. If a method annotated with org.mybatis.guice.transactional.Transactional throws an exception, the active transaction will be rolled back.
If a method annotated with org.mybatis.guice.transactional.Transactional is called and JTA does not have an active transaction, a new transaction is started. MyBatis-Guice will take care commiting or rolling back this new transaction after the method completes.

Nested calls to methods annotated with org.mybatis.guice.transactional.Transactional will all be executed in the same transaction.

Configuring TransactionManager

org.mybatis.guice.MyBatisJtaModule requires an instance of jakarta.transaction.TransactionManager. Here is some examples on how to obtain such an instance.

JavaEE 7 or CDI

@Inject TransactionManager tm;

JavaEE 6

@Resource TransactionManager tm;

OSGi service from ServiceReference

BundleContext bundleContext;
ServiceReference<TransactionManager> reference =
  bundleContext.getServiceReference(TransactionManager.class);
TransactionManager tm = bundleContext.getService(reference);

OSGi service from OSGi Enterprise Editon using lookup

InitialContext initCtx = new InitialContext();
String txName = "osgi:service/jakarta.transaction.TransactionManager"
TransactionManager tm = (TransactionManager) initCtx.lookup(txName);

OSGi Dynamic Service SCR annotation

@Component
@References({
  @Reference(
    name                = "transactionManager",
    referenceInterface  = TransactionManager.class,
    cardinality         = ReferenceCardinality.MANDATORY_UNARY,
    policy              = ReferencePolicy.STATIC,
    bind                = "bindTransactionManager",
    unbind              = "unbindTransactionManager"),
})
public MyComponent {
  TransactionManager tm;

  bindTransactionManager(TransactionManager tm) {
    this.tm = tm;
  }

  unbindTransactionManager(TransactionManager tm) {
    this.tm = null;
  }
}

Configuring DataSource

MyBatis-Guice will automatically find the DataSource used by JTA.

Configuring XAResource

org.mybatis.guice.MyBatisJtaModule will automatically create an instance of XAResource unless you bind your own provider.