Nripesh Kumar Joshi (Salesforce Developer)
Let's discuss about non setup object, setup object, mixed dml exception and how can we avoid ?
Non-setup objects typically refer to both standard and custom objects that store data, while
setup objects refer to metadata objects used for configuring and customizing the Salesforce
platform.
Non-Setup Objects:
Account
Contact
Opportunity
Case
Lead
Custom Object
Setup Objects (Metadata Objects):
Profile
PermissionSet
ApexClass
CustomMetadata
WorkflowRule
ValidationRule
RecordType
When mixed dml error is occured ?
This error will occur when we perform dml on setup and nonsetup object in single [Link]
below you can see the example.
MixedDmlExample
public class MixedDmlExample {
public static void createMixedDmlError() {
// DML operation on non-setup object (custom object)
Account acc = new Account(Name='Test Account');
insert acc;
// DML operation on setup object (User)
Profile prof = [SELECT Id FROM Profile LIMIT 1];
User user = new User(
Alias='test',
Email='test@[Link]',
EmailEncodingKey='UTF-8',
LastName='Testing',
LanguageLocaleKey='en_US',
LocaleSidKey='en_US',
ProfileId=[Link],
TimeZoneSidKey='America/New_York',
UserName='test@[Link]'
);
// This will intentionally cause a mixed DML exception
insert user;
How can we fix mixed dml exception ?
We can use future method to fix the mixed dml exception.
In below example you can see.
MixedDmlHandler
public class MixedDmlHandler {
@future
public static void processNonSetupObject(String accName) {
// DML operation on non-setup object (custom object)
Account acc = new Account(Name = accName);
insert acc;
@future
public static void processSetupObject(String userName, String profId) {
// DML operation on setup object (User)
Profile prof = [SELECT Id FROM Profile WHERE Id = :profId LIMIT 1];
User user = new User(
Alias = 'test',
Email = 'test@[Link]',
EmailEncodingKey = 'UTF-8',
LastName = 'Testing',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = [Link],
TimeZoneSidKey = 'America/New_York',
UserName = userName
);
insert user;
Now, you can call these future methods separately to avoid mixed DML issues:
ExampleController
public class ExampleController {
public static void executeMixedDml() {
// Calling the future method for non-setup object
[Link]('Test Account');
// Calling the future method for setup object
String profId = [SELECT Id FROM Profile LIMIT 1].Id;
[Link]('test@[Link]', profId);
}
}
By using future methods, you ensure that the DML operations on setup and non-setup objects
are executed in separate transactions, preventing mixed DML exceptions.