3.2.6.2.2. TransactionalDataManager

TransactionalDataManager is a bean of the middle tier which mimics the DataManager interface but can join an existing transaction. It has the following features:

  • If there is an active transaction, joins it, otherwise creates and commits a transaction same as DataManager.

  • It accepts and returns entities in detached state. The developer should load entities with appropriate views and explicitly use the save() method to save modified instances to the database.

  • It applies row-level security, works with dynamic attributes and cross-datastore references in the same way as DataManager.

Below is a simple example of using TransactionalDataManager in a service method:

@Inject
private TransactionalDataManager txDataManager;

@Transactional
public void transfer(Id<Account, UUID> acc1Id, Id<Account, UUID> acc2Id, Long amount) {
    Account acc1 = txDataManager.load(acc1Id).one();
    Account acc2 = txDataManager.load(acc2Id).one();
    acc1.setBalance(acc1.getBalance() - amount);
    acc2.setBalance(acc2.getBalance() + amount);
    txDataManager.save(acc1);
    txDataManager.save(acc2);
}

You can find more complex example in the framework test: DataManagerTransactionalUsageTest.java

TransactionalDataManager is especially useful when handling EntityChangedEvent in the current transaction. It allows you to get the current state of the changed entity from the database before the transaction is committed.