Apex - DML

Dans ce chapitre, nous verrons comment exécuter les différentes fonctionnalités de modification de base de données dans Salesforce. Il y a deux dit avec lesquels nous pouvons exécuter les fonctionnalités.

Déclarations DML

Les DML sont les actions qui sont effectuées pour effectuer une opération d'insertion, de mise à jour, de suppression, d'upsert, de restauration d'enregistrements, de fusion d'enregistrements ou de conversion de prospects.

Le DML est l'un des éléments les plus importants d'Apex, car presque tous les cas commerciaux impliquent des changements et des modifications de la base de données.

Méthodes de base de données

Toutes les opérations que vous pouvez effectuer à l'aide d'instructions DML peuvent également être effectuées à l'aide des méthodes Database. Les méthodes de base de données sont les méthodes système que vous pouvez utiliser pour effectuer des opérations DML. Les méthodes de base de données offrent plus de flexibilité que les instructions DML.

Dans ce chapitre, nous examinerons la première approche utilisant les instructions DML. Nous examinerons les méthodes de base de données dans un chapitre suivant.

Déclarations DML

Considérons maintenant à nouveau l'exemple de la société fournisseur de produits chimiques. Nos enregistrements de facture comportent des champs tels que Statut, Montant payé, Montant restant, Date de prochain paiement et Numéro de facture. Les factures qui ont été créées aujourd'hui et qui ont leur statut «En attente» doivent être mises à jour en «Payées».

Insérer une opération

L'opération d'insertion est utilisée pour créer de nouveaux enregistrements dans la base de données. Vous pouvez créer des enregistrements de n'importe quel objet standard ou personnalisé à l'aide de l'instruction Insert DML.

Example

Nous pouvons créer de nouveaux enregistrements dans l'objet APEX_Invoice__c au fur et à mesure que de nouvelles factures sont générées chaque jour pour les nouvelles commandes des clients. Nous allons d'abord créer un enregistrement client, puis nous pouvons créer un enregistrement de facture pour ce nouvel enregistrement client.

// fetch the invoices created today, Note, you must have at least one invoice 
// created today

List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
   createdDate FROM APEX_Invoice__c WHERE createdDate = today];

// create List to hold the updated invoice records
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test ABC';

//DML for Inserting the new Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
   if (objInvoice.APEX_Status__c == 'Pending') {
      objInvoice.APEX_Status__c = 'Paid';
      updatedInvoiceList.add(objInvoice);
   }
}

// DML Statement to update the invoice status
update updatedInvoiceList;

// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);

// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;

// DML which is creating the new Invoice record which will be linked with newly
// created Customer record
insert objNewInvoice;
System.debug('New Invoice Id is '+objNewInvoice.id+' and the Invoice Number is'
   + objNewInvoice.Name);

Opération de mise à jour

L'opération de mise à jour consiste à effectuer des mises à jour sur les enregistrements existants. Dans cet exemple, nous mettrons à jour le champ Statut d'un enregistrement de facture existant sur «Payé».

Example

// Update Statement Example for updating the invoice status. You have to create
and Invoice records before executing this code. This program is updating the
record which is at index 0th position of the List.

// First, fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();

// Update the first record in the List
invoiceList[0].APEX_Status__c = 'Pending';
updatedInvoiceList.add(invoiceList[0]);

// DML Statement to update the invoice status
update updatedInvoiceList;

// Prints the value of updated invoices
System.debug('List has been updated and updated values of records are' 
   + updatedInvoiceList[0]);

Opération Upsert

L'opération Upsert est utilisée pour effectuer une opération de mise à jour et si les enregistrements à mettre à jour ne sont pas présents dans la base de données, créez également de nouveaux enregistrements.

Example

Supposons que les enregistrements client dans l'objet Client doivent être mis à jour. Nous mettrons à jour l'enregistrement client existant s'il est déjà présent, sinon nous en créerons un nouveau. Cela sera basé sur la valeur du champ APEX_External_Id__c. Ce champ sera notre champ pour identifier si les enregistrements sont déjà présents ou non.

Note - Avant d'exécuter ce code, veuillez créer un enregistrement dans l'objet Client avec la valeur du champ ID externe comme '12341', puis exécutez le code ci-dessous -

// Example for upserting the Customer records
List<apex_customer__c> CustomerList = new List<apex_customer__c>();
for (Integer i = 0; i < 10; i++) {
   apex_customer__c objcust=new apex_customer__c(name = 'Test' +i,
   apex_external_id__c='1234' +i);
   customerlist.add(objcust);
} //Upserting the Customer Records

upsert CustomerList;

System.debug('Code iterated for 10 times and created 9 records as one record with 
   External Id 12341 is already present');

for (APEX_Customer_c objCustomer: CustomerList) {
   if (objCustomer.APEX_External_Id_c == '12341') {
      system.debug('The Record which is already present is '+objCustomer);
   }
}

Supprimer l'opération

Vous pouvez effectuer l'opération de suppression à l'aide du DML Supprimer.

Example

Dans ce cas, nous supprimerons les factures qui ont été créées à des fins de test, c'est-à-dire celles qui contiennent le nom «Test».

Vous pouvez également exécuter cet extrait de code à partir de la console Developer sans créer la classe.

// fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';

// Inserting the Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
   if (objInvoice.APEX_Status__c == 'Pending') {
      objInvoice.APEX_Status__c = 'Paid';
      updatedInvoiceList.add(objInvoice);
   }
}

// DML Statement to update the invoice status
update updatedInvoiceList;

// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);

// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;

// DML which is creating the new record
insert objNewInvoice;
System.debug('New Invoice Id is' + objNewInvoice.id);

// Deleting the Test invoices from Database
// fetch the invoices which are created for Testing, Select name which Customer Name
// is Test.
List<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c
   WHERE APEX_Customer__r.Name = 'Test'];

// DML Statement to delete the Invoices
delete invoiceListToDelete;
System.debug('Success, '+invoiceListToDelete.size()+' Records has been deleted');

Annuler la suppression

Vous pouvez annuler la suppression de l'enregistrement qui a été supprimé et qui se trouve dans la corbeille. Toutes les relations que possède l'enregistrement supprimé seront également restaurées.

Example

Supposons que les enregistrements supprimés dans l'exemple précédent doivent être restaurés. Ceci peut être réalisé en utilisant l'exemple suivant. Le code de l'exemple précédent a été modifié pour cet exemple.

// fetch the invoice created today
List<apex_invoice__c> invoiceList = [SELECT id, Name, APEX_Status__c,
createdDate FROM APEX_Invoice__c WHERE createdDate = today];
List<apex_invoice__c> updatedInvoiceList = new List<apex_invoice__c>();
APEX_Customer__c objCust = new APEX_Customer__C();
objCust.Name = 'Test';

// Inserting the Customer Records
insert objCust;
for (APEX_Invoice__c objInvoice: invoiceList) {
   if (objInvoice.APEX_Status__c == 'Pending') {
      objInvoice.APEX_Status__c = 'Paid';
      updatedInvoiceList.add(objInvoice);
   }
}

// DML Statement to update the invoice status
update updatedInvoiceList;

// Prints the value of updated invoices
System.debug('List has been updated and updated values are' + updatedInvoiceList);

// Inserting the New Records using insert DML statement
APEX_Invoice__c objNewInvoice = new APEX_Invoice__c();
objNewInvoice.APEX_Status__c = 'Pending';
objNewInvoice.APEX_Amount_Paid__c = 1000;
objNewInvoice.APEX_Customer__c = objCust.id;

// DML which is creating the new record
insert objNewInvoice;
System.debug('New Invoice Id is '+objNewInvoice.id);

// Deleting the Test invoices from Database
// fetch the invoices which are created for Testing, Select name which Customer Name
// is Test.
List<apex_invoice__c> invoiceListToDelete = [SELECT id FROM APEX_Invoice__c
   WHERE APEX_Customer__r.Name = 'Test'];

// DML Statement to delete the Invoices
delete invoiceListToDelete;
system.debug('Deleted Record Count is ' + invoiceListToDelete.size());
System.debug('Success, '+invoiceListToDelete.size() + 'Records has been deleted');

// Restore the deleted records using undelete statement
undelete invoiceListToDelete;
System.debug('Undeleted Record count is '+invoiceListToDelete.size()+'. This should 
   be same as Deleted Record count');