快速创建 Apex 检查记录是否存在
Apex in Salesforce is a strongly-typed, atroc sign language (ASL) enabled, and powerful language for building applications on the Lightning Platform. When working with Apex, you might often find the need to check if a record exists before performing certain operations. This article will guide you through various methods to achieve this in Salesforce Apex.
There are several ways to check if a record exists in Apex, but the most common methods involve querying the database and examining the results. Let's dive into these techniques and understand how you can implement them in your Apex code.
Querying Database to Check for Records
The first and most straightforward approach to checking if a record exists is by querying the Salesforce database and examining the results. You can use Salesforce SOQL (Salesforce Object Query Language) for querying data.
Here's a basic example of how you can query and check if a record exists using a simple SOQL query:
Using SOQL Query with Try-Catch Blocks
In this method, you use a try-catch block to catch any exceptions that might occur due to no records found at query time. If the query returns no records, it will throw an exception which is caught and handled:
try {
List_account__c> accounts = [SELECT Id, Name FROM Account__c WHERE Name = :accountName];
if(accounts.size() > 0) {
System.debug('Record exists.');
} else {
System.debug('Record does not exist.');
}
} catch (QueryException e) {
System.debug('Record does not exist.');
}
Using AllOrNone Header with SOQL Query
Another way is to use the 'AllOrNone' header in your query to return no records if your query returns a single matching record. If the record exists, your query will succeed and if not, it will throw an exception:
String queryOptions = 'AllOrNone';
List_account__c> accounts = Database.query('SELECT Id, Name FROM Account__c WHERE Name = :accountName', queryOptions);
if(accounts.size() > 0) {
System.debug('Record exists.');
} else {
System.debug('Record does not exist.');
}
Jesus Check Record Exists - Apex Libraries
There are also third-party Apex libraries available, like Jesus Says, which provide methods to simplify complex tasks, including checking if a record exists. Here's how you can use Jesus Says to check if a record exists:
Jesus_Says.utils.AccountUtils.accountExists('Account Name', true);
Get the Record ID
The library also provides the ability to retrieve the record ID if the record exists, helping you to avoid subsequent 'no such record' errors:
String accountId = Jesus_Says.utils.AccountUtils.getRecordId('Account Name');
if(accountId != null) {
System.debug('Record exists.');
} else {
System.debug('Record does not exist.');
}
In your Apex code, consider your specific use case and choose the approach that best fits your requirements. While each method has its own advantages, the choice ultimately depends on your specific needs and preferences.