Database Methods and process of executing the Apex class in Salesforce

Last updated on Nov 24 2021
Abha Kulkarni

Table of Contents

Database Methods and process of executing the Apex class in Salesforce

Database class methods is differently of working with DML statements which are more flexible than DML Statements like insert, update, etc.

Differences between Database Methods and DML Statements

DML Statements Database Methods
Partial Update isn’t allowed. For instance, if you have 20 records in list, then either all the records will be updated or none. Partial update is allowed. You’ll specify the Parameter in Database method as true or false, faithfull allow the partial update and false for not allowing an equivalent
You cannot get the list of success and failed records. You’ll get the list of success and failed records as we’ve  seen within the example.
Example − insert listName Example − Database.insert(listName, False), where false indicate that partial update isn’t allowed.

Insert Operation

Inserting new records via database methods is additionally quite simple and versatile . allow us to consider the previous scenario wherein, we’ve inserted new records using the DML statements. we’ll be inserting an equivalent using Database methods.
Example

// Insert Operation Using Database methods
// Insert Customer Records First using simple DML Statement. This Customer Record are going to be 
// used once we will create Invoice Records
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';
insert objCust; // Inserting the Customer Records

// Insert Operation Using Database methods
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
List InvoiceListToInsert = new List();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Customer__c = objCust.id;
objNewInvoice.APEX_Amount_Paid__c = 1000;
InvoiceListToInsert.add(objNewInvoice);
Database.SaveResult[] srList = Database.insert(InvoiceListToInsert, false);

// Database method to insert the records in List
// Iterate through each returned result by the tactic

for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition are going to be executed for successful records and can fetch the ids 
// of successful records
System.debug('Successfully inserted Invoice. Invoice ID: ' + sr.getId());
// Get the invoice id of inserted Account
} else {
// This condition are going to be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');

// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are suffering from the error:' 
+ objErr.getFields());
}
}
}

Update Operation

Let us now consider our business case example using the database methods. Suppose we’d like to update the status field of Invoice object but at an equivalent time, we also require information like status of records, failed record ids, success count, etc. this is often impossible by using DML Statements, hence we must use Database methods to urge the status of our operation.
Example
We will be updating the Invoice’s ‘Status’ field if it’s in status ‘Pending’ and date of creation is today.
The code given below will help in updating the Invoice records using the Database.update method. Also, create an Invoice record before executing this code.

// Code to update the records using the Database methods
List invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];

// fetch the invoice created today
List updatedInvoiceList = new List();
for (APEX_Invoice__c objInvoice: invoiceList) {
if (objInvoice.APEX_Status__c == 'Pending') {
objInvoice.APEX_Status__c = 'Paid';
updatedInvoiceList.add(objInvoice); //Adding records to the list
}
}

Database.SaveResult[] srList = Database.update(updatedInvoiceList, false);
// Database method to update the records in List

// Iterate through each returned result by the tactic 
for (Database.SaveResult sr : srList) {
if (sr.isSuccess()) {
// This condition are going to be executed for successful records and can fetch
// the ids of successful records
System.debug('Successfully updated Invoice. Invoice ID is : ' + sr.getId());
} else {
// This condition are going to be executed for failed records
for(Database.Error objErr : sr.getErrors()) {
System.debug('The following error has occurred.');

// Printing error message in Debug log
System.debug(objErr.getStatusCode() + ': ' + objErr.getMessage());
System.debug('Invoice oject field which are suffering from the error:' 
+ objErr.getFields());
}
}
}

We will be watching only the Insert and Update operations during this tutorial. the opposite operations are quite almost like these operations and what we did within the last chapter.

Apex – Invoking

Apex invoking refers to the method of executing the Apex class. Apex class can only be executed when it’s invoked via one among the ways listed below −
• Triggers and Anonymous block
• A trigger invoked for specified events
• Asynchronous Apex
• Scheduling an Apex class to run at specified intervals, or running a batch job
• Web Services class
• Apex Email Service class
• Apex Web Services, which permit exposing your methods via SOAP and REST Web services
• Visualforce Controllers
• Apex Email Service to process inbound email
• Invoking Apex Using JavaScript
• The Ajax toolkit to invoke Web service methods implemented in Apex
We will now understand a couple of common ways to invoke Apex.

Salesforce 13
Salesforce

From Execute Anonymous Block

You can invoke the Apex class via execute anonymous within the Developer Console as shown below −
Step 1 − Open the Developer Console.
Step 2 − Click on Debug.

Salesforce 14
Salesforce

Step 3 − Execute anonymous window will open as shown below. Now, click on the Execute button −

Salesforce 15
Salesforce

Step 4 − Open the Debug Log when it’ll appear within the Logs pane.

Salesforce 16
Salesforce

From Trigger

You can call an Apex class from Trigger also . Triggers are called when a specified event occurs and triggers can call the Apex class when executing.
Following is that the sample code that shows how a category gets executed when a Trigger is named .
Example

// Class which can gets called from trigger
public without sharing class MyClassWithSharingTrigger {

public static Integer executeQuery (List CustomerList) {
// perform some logic and operations here
Integer ListSize = CustomerList.size();
return ListSize;
}
}

// Trigger Code
trigger Customer_After_Insert_Example on APEX_Customer__c (after insert) {
System.debug('Trigger is named and it'll call Apex Class');
MyClassWithSharingTrigger.executeQuery(Trigger.new); // Calling Apex class and 
// method of an Apex class
}

// this instance is for reference, no got to execute and can have detail look on 
// triggers later chapters.

From Visualforce Page Controller Code

Apex class are often called from the Visualforce page also . we will specify the controller or the controller extension and therefore the specified Apex class gets called.
Example
VF Page Code

Salesforce 17
Salesforce

Apex Class Code (Controller Extension)

Salesforce 18
Salesforce

So, this brings us to the end of blog. This Tecklearn ‘Database Methods and process of executing the Apex class in Salesforce’ blog helps you with commonly asked questions if you are looking out for a job in Salesforce. If you wish to learn Salesforce and build a career in Salesforce domain, then check out our interactive, Salesforce Certification Training: Admin 201 and App Builder, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Salesforce Certification Training: Admin 201 and App Builder

Salesforce Certification Training: Admin 201 and App Builder

About the Course

Salesforce Certification Training course will help you pass the Salesforce Administrator Exam (Admin 201) and the Salesforce App Builder (Dev 401) Exam. Concepts on Force.com Platform, AppExchange, SFDC Security Model, Service Cloud, Sales Cloud, Lightning App Builder, Salesforce Reports & Dashboard can be mastered in this Salesforce Training course. You can also configure the platform, manage users, find better ways to use the platform’s features, build applications with Salesforce Lightning, and more. Further, in this Salesforce certification training course, you will master App builder, Apex, Visualforce, etc.

Why Should you take Salesforce Admin 201 and App Builder Training?

• As per Indeed.com data, 200% global jump in Salesforce jobs since Jan 2016. Salesforce Certified Administrators earn an annual average salary of $87,000 but can go as high as $160,000 depending on their knowledge, skills, and experience.
• More than 200,000 companies worldwide use Salesforce platform. Salesforce leads the CRM market with 19.5 percent of market share – Forbes.
• The global CRM software market will reach US$40.26 billion in 2023, up from US$36.9 billion (2020) – Statista.

What you will Learn in this Course?

Salesforce Fundamentals

• Introduction to CRM concepts and Cloud computing
• Salesforce.com Overview and Fundamentals
• Understanding Salesforce Platform
Understanding Salesforce Platform
• Understanding Salesforce Terminologies and Introducing the force.com platform
• Understanding Salesforce Metadata and API
• Describe the capabilities of the core CRM objects in the Salesforce schema
• Identify common scenarios for extending an org using the AppExchange
• About Salesforce Certification
Introduction to Sales Cloud
• Sales Cloud
• Sales Process
• Sales Productivity Features
• Lead Management
• Lead auto response
• Lead assignment
• Web to lead
• Accounts and Contacts Management
• Opportunities
• Campaign Management
Security Model, User Management and Its Features
• Security Model Mind Map
• System Level or Org Level Security
• User Administration and Troubleshooting
• Permission Sets
• Profile Management
• User Actions
• Assigning Permission
• Session settings
• Activations
• Page layout assignment
• Tab setting
• Field level security
Object, Record and Field Level Features
• Custom Object
• Custom Field
• Data Types
• Relationship among Objects
• Working with App and Tabs
Data Handling and Processing
• Data Import and Export with Salesforce
• Insert, Update and Delete Data with Salesforce
• Export Data with UI
• Export Data using Data Loader Tool
Deployment
• SandBox
• Moving Data from SB to Production – Deployment
• Types of SandBox
• Change Sets
• Types of Change Sets
Application Cycle
• Milestones
• Sandboxes
• Change Sets
• Packages
Reports and Dashboards
Declarative Implementation in Salesforce
Salesforce Development and Apex Programming
• Apex Programming
• Apex Classes
• Apex Settings
• SOQL – Salesforce Object Query Language
• DML Commands
• Apex Class in Detail
• Apex Triggers
• Apex Testing
• Access Specifier in Salesforce
• Testing
Lightning in Salesforce
• Lightning Components
• Lightning Component Capabilities
• Lightning Components vs. Visualforce
Visual Force in Salesforce
• Standard Visualforce controller and controller extensions,
• Visualforce Page
• Understanding the MVC Pattern
• Tools for Visualforce Development
• Visual Force Components
WorkFlows in Salesforce
• Work Flows in Salesforce
• Types of Work Flows
• Work Flows Rules
About Preparation of Salesforce 201 and App Builder Certification exams

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "Database Methods and process of executing the Apex class in Salesforce"

Leave a Message

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