> For the complete documentation index, see [llms.txt](https://bxorm.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bxorm.ortusbooks.com/usage/transactions.md).

# Transactions

Learn transaction management with bx-orm

A transaction is any discrete unit of work used to pool database queries and statements to execute at once. This helps us to prevent a failed update from leaving the database in a broken state.

To denote a transaction, we wrap it in the `transaction{}` tag:

```js
transaction{
    // queries go here
}
```

The transaction will automatically commit (persist) at the end of the transaction block.

{% hint style="warning" %}
**Transaction Scope:** Transaction events are persisted across **ALL** ORM datasources. This means that:

* **Transaction begin** - begins a transaction on every ORM datasource referenced by an ORM entity
* **Transaction commit** - commits changes on every ORM datasource
* **Transaction rollback** - rolls back changes on every ORM datasource
* **Transaction end** - ends the transaction on every ORM datasource

When you initiate a transaction, it affects **all** datasources that have been referenced by ORM entities, not just a single datasource as in normal Boxlang transaction management.
{% endhint %}

## Transaction Rollback

A transaction rollback undoes all changes made within the transaction block and prevents them from being persisted to the database. This is useful when an error occurs or business rules are violated.

### Automatic Rollback on Error

If an exception occurs within a transaction block, the transaction is automatically rolled back:

```js
try {
    transaction {
        var user = entityNew( "User" );
        user.setUsername( "johndoe" );
        entitySave( user );
        
        // This will throw an exception and trigger automatic rollback
        var invalid = entityLoadByPK( "NonExistentEntity", 1 );
    }
} catch ( any e ) {
    // Transaction has been rolled back, user was not saved
    writeOutput( "Error: #e.message#" );
}
```

### Manual Rollback

You can manually trigger a rollback using `transactionRollback()`:

```js
transaction {
    var account = entityLoadByPK( "Account", 1 );
    var newBalance = account.getBalance() - 100;
    
    // Business rule: account balance cannot go negative
    if ( newBalance < 0 ) {
        transactionRollback();
        writeOutput( "Insufficient funds - transaction rolled back" );
    } else {
        account.setBalance( newBalance );
        entitySave( account );
        // Transaction commits automatically at end of block
    }
}
```

The alternative syntax `action="rollback"` is also supported.

## Transaction Commit

A transaction commit persists all changes made within the transaction block to the database. By default, transactions automatically commit when the transaction block completes successfully.

### Automatic Commit

When a transaction block completes without errors or explicit rollback, it will be automatically committed:

```js
transaction {
    // Create a new user
    var user = entityNew( "User" );
    user.setUsername( "janedoe" );
    user.setEmail( "jane@example.com" );
    entitySave( user );
    
    // Create a profile for the user
    var profile = entityNew( "Profile" );
    profile.setUser( user );
    profile.setBio( "Software developer" );
    entitySave( profile );
    
    // Both saves commit together at the end of this block
}
```

### Manual Commit

You can manually commit a transaction using `transactionCommit()` when you need to persist changes before the end of the block:

```js
transaction {
    // First batch of operations
    var batch1 = entityNew( "Batch" );
    batch1.setName( "Batch 1" );
    entitySave( batch1 );
    transactionCommit();
    writeOutput( "Batch 1 committed successfully" );
    
    // Second batch of operations
    var batch2 = entityNew( "Batch" );
    batch2.setName( "Batch 2" );
    entitySave( batch2 );
    transactionCommit();
    writeOutput( "Batch 2 committed successfully" );
}
```

The alternative syntax `action="commit"` is also supported.

{% hint style="warning" %}
**Important:** When you manually commit a transaction using `transactionCommit()`, it effectively closes the current transaction and immediately begins a new one. This means that any subsequent operations within the transaction block will be part of a new transaction context.
{% endhint %}

### Named Transactions

Named transactions allow you to commit or rollback specific transactions when dealing with nested transactions:

```js
transaction name="outer" {
    var customer = entityNew( "Customer" );
    customer.setName( "Acme Corp" );
    entitySave( customer );
    
    transaction name="inner" {
        var invoice = entityNew( "Invoice" );
        invoice.setCustomer( customer );
        invoice.setAmount( 1000.00 );
        entitySave( invoice );
        
        // Commit only the inner transaction
        transactionCommit( "inner" );
    }
    
    // Outer transaction commits automatically
}
```

## Transaction Savepoint

True database savepoints (`SAVEPOINT` / `ROLLBACK TO SAVEPOINT`) are not *currently* supported on ORM transactions - you cannot partially roll back a transaction to an intermediate point.

Nested `transaction` blocks are still tracked internally: when an inner (child) `transaction` block ends, bx-orm flushes the Hibernate session for each active datasource so that its changes are pushed to the database before the outer transaction continues. This keeps nested transaction blocks well-behaved, but it is not a substitute for real savepoint/rollback support.

{% hint style="info" %}
Looking for full ORM savepoint support? [Contact our Support team to consider sponsoring this feature](https://boxlang.io/plans).
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://bxorm.ortusbooks.com/usage/transactions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
