Unrestricted Queries in Salesforce Web Services | Apex and Visualforce Controllers

Annotation for Unrestricted Queries in Salesforce Web Services

Question

What annotation can be used with Web Services to allow unrestricted queries when no DML operations are necessary?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The correct answer to this question is A. @ReadOnly.

In Apex, @ReadOnly is an annotation that can be used to indicate that a method or class does not modify any data. When applied to a Web Service method, @ReadOnly allows unrestricted queries to be executed, even if the user's profile would normally restrict the query.

This can be useful in situations where you need to retrieve a large amount of data from Salesforce but do not need to modify it. By using @ReadOnly, you can avoid hitting governor limits on queries and improve performance.

For example, suppose you have a Visualforce page that displays a list of all contacts in your Salesforce org. You could use a controller method with the @ReadOnly annotation to retrieve the list of contacts and pass it to the Visualforce page:

java
@RestResource(urlMapping='/contacts') global with sharing class ContactWebService { @HttpGet global static List<Contact> getContacts() { // Use the @ReadOnly annotation to allow unrestricted queries // even if the user's profile would normally restrict them. return [SELECT Id, Name, Email FROM Contact] WITH SECURITY_ENFORCED; } }

Note that the WITH SECURITY_ENFORCED clause is used here to ensure that the query respects the sharing rules and field-level security of the user. This is important to ensure that sensitive data is not leaked to unauthorized users.

In contrast, options B (for loops), C (RETURNING), and D (TRUE) are not related to Web Services or query restrictions in Apex. For loops are used to iterate over collections, RETURNING is used to return values from DML statements, and TRUE is a Boolean literal with a value of true.