Apex - DML

In questo capitolo, discuteremo come eseguire le diverse funzionalità di modifica del database in Salesforce. Ci sono due modi con cui possiamo eseguire le funzionalità.

Dichiarazioni DML

DML sono le azioni che vengono eseguite per eseguire operazioni di inserimento, aggiornamento, eliminazione, upsert, ripristino di record, unione di record o conversione di lead.

DML è una delle parti più importanti in Apex poiché quasi tutti i casi aziendali comportano modifiche e modifiche al database.

Metodi di database

Tutte le operazioni che è possibile eseguire utilizzando le istruzioni DML possono essere eseguite anche utilizzando i metodi del database. I metodi di database sono i metodi di sistema che è possibile utilizzare per eseguire operazioni DML. I metodi di database offrono maggiore flessibilità rispetto alle istruzioni DML.

In questo capitolo, esamineremo il primo approccio che utilizza le istruzioni DML. Analizzeremo i metodi del database in un capitolo successivo.

Dichiarazioni DML

Consideriamo ora di nuovo l'istanza dell'azienda fornitrice di prodotti chimici. I nostri record fattura hanno campi come Stato, Importo pagato, Importo rimanente, Prossima data di pagamento e Numero fattura. Le fatture che sono state create oggi e hanno il loro stato "In sospeso", dovrebbero essere aggiornate a "Pagate".

Inserisci operazione

L'operazione di inserimento viene utilizzata per creare nuovi record nel database. È possibile creare record di qualsiasi oggetto standard o personalizzato utilizzando l'istruzione Insert DML.

Example

Possiamo creare nuovi record nell'oggetto APEX_Invoice__c poiché ogni giorno vengono generate nuove fatture per i nuovi ordini dei clienti. Creeremo prima un record cliente, quindi possiamo creare un record fattura per quel nuovo record cliente.

// 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);

Operazione di aggiornamento

L'operazione di aggiornamento consiste nell'eseguire gli aggiornamenti sui record esistenti. In questo esempio, aggiorneremo il campo Stato di un record Fattura esistente in "Pagato".

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]);

Operazione Upsert

L'operazione Upsert viene utilizzata per eseguire un'operazione di aggiornamento e se i record da aggiornare non sono presenti nel database, crea anche nuovi record.

Example

Supponiamo che i record del cliente nell'oggetto Cliente debbano essere aggiornati. Aggiorneremo il record del cliente esistente se è già presente, altrimenti ne creeremo uno nuovo. Questo sarà basato sul valore del campo APEX_External_Id__c. Questo campo sarà il nostro campo per identificare se i record sono già presenti o meno.

Note - Prima di eseguire questo codice, creare un record nell'oggetto Cliente con il valore del campo Id esterno come "12341" e quindi eseguire il codice indicato di seguito -

// 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);
   }
}

Elimina operazione

È possibile eseguire l'operazione di eliminazione utilizzando Elimina DML.

Example

In questo caso, cancelleremo le fatture che sono state create a scopo di test, cioè quelle che contengono il nome come 'Test'.

Puoi eseguire questo snippet anche dalla Console per gli sviluppatori senza creare 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');

Ripristina operazione

È possibile ripristinare il record che è stato eliminato ed è presente nel Cestino. Verranno ripristinate anche tutte le relazioni che ha il record eliminato.

Example

Supponiamo che i record eliminati nell'esempio precedente debbano essere ripristinati. Ciò può essere ottenuto utilizzando il seguente esempio. Il codice nell'esempio precedente è stato modificato per questo esempio.

// 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');