ApexSensei

Drills › Debug it

Fix a mixed DML error

Debug it · Advanced · 20 min · Runs in your Salesforce Developer org · Apex Path

Scenario. The new-customer screen creates an Account and a login for the new account manager in one click. In production, every click fails with MIXED_DML_OPERATION.

Onboarding creates an Account and a User in one method. In production that throws MIXED_DML_OPERATION. Move the User insert into its own transaction.

What you will learn

Setup objects such as User are one family; Account is in the other. In production, saving a User with a role and an Account in one transaction throws MIXED_DML_OPERATION.

Give the setup DML its own transaction with an @future method:

@future
public static void createUser(String lastName) {
    insert build(lastName);
}

Gotcha. @future methods take only primitives, never a record. The checks prove the User is missing before the transaction ends and present after.

The task

Fix onboard so the Account is created now and the User is created in a separate transaction.

Examples:

  • onboard('Northwind', 'Rivera') → the Account exists right away
  • before the transaction ends → no User with LastName Rivera exists yet
  • after the transaction ends → a User with LastName Rivera exists

Requirements:

  1. Keep the Account insert where it is.
  2. Add a static method with @future that builds and inserts the User. Pass the last name in, not the User.
  3. Call that method from onboard instead of inserting the User directly. Remove the direct insert.
  4. Keep using the provided UserBuilder to build the User.

Starter code

public class AS_2CA250FAD60D_Onboarding {
    public static void onboard(String accountName, String lastName) {
        insert new Account(Name = accountName);
        insert AS_2CA250FAD60D_UserBuilder.build(lastName);
    }
}

When it passes

The Account saves in the current transaction. The User saves in a future transaction, so the two families never mix. Before the transaction ends there is no User; after it there is one. One click queues one future call.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Stop a trigger calling itself · Fix a Batch job that forgets its count ›