Salesforce/Apex: When does a MIXED_DML_OPERATION error come?

Varun   Varun 469 Views
DML operations on certain sObjects can not be mixed with other sObjects in the same transaction. Certain sObjects affect the user?s access to records in the organization.

sObjects must be inserted or updated in a different transaction to prevent operations from happening with incorrect access level permissions. For example, you can?t update an account and a user role in a single transaction. However, there are no restrictions on delete DML operations.

In order to resolve this issue, we can perform DML on regular sobject in a transaction and DML on those sObject can be performed in asynchronous call like ( future job or  a class which implements Queueable interface ).

Example with future method:

public class MixedDMLFuture {
    public static void createAccountAndAddUserToRole() {
        Account a = new Account(Name='Acme');
        insert a;
        Util.insertUserWithRole(
            'abc@xyz.com', 'raj', 
            'bean@exe.com', 'kumar');        
    }
}

public class Util {
    @future
    public static void insertUserWithRole( // per form role object UserRole } }
Some object which are candidate for MIXED DML ERROR

  • FieldPermissions
  • Group
  • GroupMember
  • ObjectPermissions
  • PermissionSet
  • PermissionSetAssignment
  • QueueSObject
  • ObjectTerritory2AssignmentRule
  • ObjectTerritory2AssignmentRuleItem
  • RuleTerritory2Association
  • SetupEntityAccess
  • Territory2
  • Territory2Model
  • UserTerritory2Association
  • User