Mix DML Operation

DML operations on certain sObjects, sometimes referred to as setup objects, can’t be mixed with DML on other sObjects 
in the same transaction. This restriction exists because some sObjects affect the user’s access to records in the org. 
You must insert or update these types of sObjects 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, deleting a DML operation has no restrictions.
You can’t use the FieldPermissions and Group with other sObjects when performing DML operations in the same transaction.

You can perform DML operations on more than one type of sObject in a single class using the following process:
1. Create a method that performs a DML operation on one type of sObject.
2. Create a second method that uses the future annotation to manipulate a second sObject type.

This example shows how to perform mixed DML operations by using a future method to perform a DML operation on the User object.

public class MixedDMLFuture 
{
    public static void useFutureMethod() 
{
        // First DML operation
        Account a = new Account(Name='Acme');
        insert a;
        
        // This next operation (insert a user with a role) 
        // can't be mixed with the previous insert unless 
        // it is within a future method. 
        // Call future method to insert a user with a role.
        Util.insertUserWithRole(
            'mruiz@awcomputing.com', 'mruiz', 
            'mruiz@awcomputing.com', 'Ruiz');        
    }
}

public class Util 
{
    @future
    public static void insertUserWithRole(String uname, String al, String em, String lname) 
{
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
        UserRole r = [SELECT Id FROM UserRole WHERE Name='COO'];
        // Create new user with a non-null user role ID 
        User u = new User(alias = al, email=em, 
            emailencodingkey='UTF-8', lastname=lname, 
            languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
            timezonesidkey='America/Los_Angeles', 
            username=uname);
        insert u;
    }
}

Mixed DML Operations in Test Methods:
Test methods allow for performing mixed Data Manipulation Language (DML) operations that include both setup sObjects 
and other sObjects if the code that performs the DML operations is enclosed within System.runAs method blocks. 
You can also perform DML in an asynchronous job that your test method calls. 
These techniques enable you, for example, to create a user with a role and other sObjects in the same test.

Comments

Popular Posts