Skip to content

Transactions

ZorT edited this page Jul 30, 2023 · 8 revisions

Note: Transaction management is currently experimental feature and can be changed or removed in the future releases.

Basic Usage

We allow you to easily enable and manage connection transaction. You can read more about SQL connection transactions in this article.
To activate transaction mode, run:

SQLDatabaseConnection connection = ...;
Transaction transaction = connection.beginTransaction();

You can perform variety of actions with the connection, including:

transaction.commit(); // Commit the transaction
transaction.rollback(); // Rollback changes
transaction.close(); // Close transaction

boolean notCommited = transaction.isActive(); // Transaction commit state

Transaction Flow (Chain of queries)

You can create chain of queries in the transaction to be executed in queue. When any of the queries fails, you can make the flow auto rollback.
Example of simple transaction flow usage:

// Your code
String user = ...;
int money = ...;
int resources = ...;

// Initialize transaction
SQLDatabaseConnection connection = ...;
Transaction transaction = connection.beginTransaction();
UpdateQuery updateMoneyQuery = new UpdateQuery()
  .table("users_money")
  .set("money", money)
  .where().isEqual("username", user);
UpdateQuery updateResourcesQuery = new UpdateQuery()
  .table("users_resources")
  .set("resources", resources)
  .where().isEqual("username", user);

// Group of queries that depend on each other
TransactionFlow.Result result = transaction.flow()
  .rollbackOnFailure(true) // Rollback all changes if error occurs
  .commitOnSuccess(true) // Commit transaction if every part succeeds
  .autoClose(true) // Close transaction after process
  .step(updateMoneyQuery)
  .step(updateResourcesQuery)
  .execute();

if (!result.isSuccessful()) {
  int brokenIndex = result.getBrokenIndex(); // Where the flow failed
  if (brokenIndex == 0) {
    System.out.println("Changing user money failed!");
  } else if (brokenIndex == 1) {
    System.out.println("Changing user resources count failed!")
  }
}
Clone this wiki locally