In this post, we will be using an example where we want to bypass sharing for DML operation in a Apex class running in a user mode, without changing the object’s OWD.

In your main class, create an inner class with declaration as ‘without sharing’. Inside this class create a method which performs DML operation. Call this method from your main class.

public with sharing class BypassSharingDemo 
{
    private void createAccount()
    {
        Account account = new Account();
        account.Name = 'Test Account';

        BypassSharing bypassSharing = new BypassSharing();
        bypassSharing.insertAccount(account);
    }

    private without sharing class BypassSharing
    {
	private void insertAccount(Account item)
	{
	     Database.insert(item);
	}
    } 
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *