[SalesForce] Apex transaction

What does it mean? If I have code that get fired any trigger, It's form with him one apex transaction?(Or my code and code that executes in trigger are two separated apex transactions?)

An Apex transaction represents a set of operations that are executed as a single unit. All DML operations in a transaction either complete successfully, or if an error occurs in one operation, the entire transaction is rolled back and no data is committed to the database. The boundary of a transaction can be a trigger, a class method, an anonymous block of code, a Visualforce page, or a custom Web service method.

All operations that occur inside the transaction boundary represent a single unit of operations. This also applies for calls that are made from the transaction boundary to external code, such as classes or triggers that get fired as a result of the code running in the transaction boundary.

Best Answer

An individual request to Salesforce forms a single transaction. If the request is from a page button for example, the changes made by the controller and any triggers that fire and other declarative logic such as workflow rules all occur within a single transaction meanings they all succeed or all fail (rollback) together. The same is true for web service calls into Salesforce. This ensures that work is not left half done.

When you initiate asynchronous Apex from a transaction, the asynchronous Apex runs in a separate transaction (or transactions for batchable apex where the start, multiple executes and the end are all separate transactions). Note that if the initiating transaction fails (rolls back) the asynchronous Apex will not execute at all.

Most of the time the platform handles the transaction logic for you and there is no need to try to intervene. Occasionally you may find some use for a Savepoint and explicit Rollback as described in the Transaction Control.

Related Topic