Transactions

We can use explicit transactions to wrap multiple database actions such as queries or persisting via save() etc.

try (Transaction transaction = ebeanServer.beginTransaction()) {

  // do stuff...
  Customer customer = ...
  customer.save();

  Order order = ...
  order.save();

  transaction.commit();
}

We can alternatively use Ebean's @Transactional annotation on methods or Spring Transactions or JTA Transactions.

@Transactional
public void process(OffsetDateTime startOffset) {
  ...
}

Implicit transactions

When no transactions are specified explicitly Ebean will create a transaction to perform the action.

Query - read only transaction

For queries Ebean will look to use a read only transaction. If a Read Only DataSource has be configured Ebean will look to use that by default.

Save, Insert, Update

For all persist requests like save, insert, update, delete Ebean will create a transaction and perform a COMMIT at the end of the operation.

Programmatic

We programmatically create transactions using ebeanServer.beginTransaction(). When we do so we generally should use try with resources to ensure that the transaction is closed regardless of an exception throw.

// use try with resources such that the transaction is
// always closed, even if an exception is thrown
try (Transaction transaction = ebeanServer.beginTransaction()) {

  // do good stuff...
  customer.save();
  order.save();

  transaction.commit();
}

Kotlin transaction.use { }

Kotlin use is used similarly to try with resources to ensure the transaction is closed.

Country.db().beginTransaction().use { transaction ->

  transaction.isBatchMode = true

  Country("FJ", "Fiji").save()
  Country("TO", "Tonga").save()
  Country("WS", "Samoa").save()

  transaction.commit()
}

@Transactional

We can put @Transactional annotation on methods (including private methods) and Ebean enhancement will add transaction demarcation to those methods.

@Transactional
public void process(OffsetDateTime startOffset) {
  ...
}

ebean.mf

For the @Transactional to work we need to make sure the ebean.mf manifest file specifies the packages that contain the classes annotated with @Transactional such that they are enhanced.

The ebean.mf file is typically located in src/main/resources/ebean.mf.

Example ebean.mf

entity-packages: org.example.domain
transactional-packages: org.example
querybean-packages: none

With the example above we are enhancing @Transactional methods for classes in org.example and any sub-packages.

Reference: docs/introduction/manifest

Note that the CLI Command line tool can generate the ebean.mf file so look to use that if you like.

Edit Page