I am new to salesforce, what is the difference between apex managed sharing and withsharing ?

we already have multiple way to share the records like sharing rules,criteria based,mannual sharing , hierarchy level sharing, owd then what is the extra feature have with apex managed sharing, which case we would prefer this? and which case we would prefer withsharing key word?

Please clear my confussion

Thanks in advance


Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically through Apex or the SOAP API.

For example, If you have custom object called "JOB" and you want to make sure whenever JOB record is created access should be granted to HR manager. You need to use Apex managed sharing to share the record with HR manager with the help of trigger/Class/API.

On other hand, the with sharing keyword allows you to specify that the sharing rules for the current user be taken into account for a class. For example, User has a record read only permission as per sharing rule, you created a class using keyword With Sharing and updating some of the field then it won't allow you to update the field but in case keyword "Without Sharing" it would allow you to update the class.

In simple word, Apex Managed Sharing is used to grant the access to the records. Keyword "With Sharing" is used to respect the current user sharing rule.

| improve this answer | |

The examples you list like sharing rules and Organisation-Wide-Defaults are all just ways of managing sharing declaratively (e.g. without code). There are different layers to this as you can control access at an object-level, at a field-level and at a record-level.

Apex Managed Sharing allows you to create more sophisticated sharing rules than the declarative tools allow. Crucially these can be dynamic. For example, you can used Apex Managed Sharing to write a trigger that will share a record with a user specified in a lookup field (this example comes from the docs).

The with sharing keyword simply ensures that the class takes into account the sharing rules for the current user. This overrides the default position where Apex is set to run in System context which automatically has access to all objects, records and fields.

In summary, Apex Managed Sharing is about programmatically configuring sharing rules whereas with sharing is about enforcing existing sharing rules for the Apex class.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.