I got a query from one of the salesforce developer about DML operations in Salesforce. Here is the query :
Why there are two ways of doing DML operation in Slaesforce ?
1. Insert objectlist;
2. Database.insert(objectlist);
My thought on this:
Transaction control:
Use method 1 when you do not need to have a control over the transaction or you do not need a transaction roll back strategy. Use method 2 when you need to have a transaction control. But it’s always better have a transaction controll in place which you are coding. This will give you more control over you transaction and will save you lots of major issues down the line. You can have propper data integrity in your org. If certain portion of the transaction fails you can roll back entire transaction or a part of it.
Partial or full operation :
Using method 1 will fail for entire list of records or will be successful for entire list of records. It will not insert 2 records from a list of 10 and fail for 8 of them. But if you are using Database.insert then you can specify whether all 10 should get inserted into the system or some of them can be inserted. In this case if 2 of the records in a list of 10 records don’t qualify then just these two will not be inserted and rest 8 can be inserted into the system.
Error handling : Using the 1st method you can capture one error for the entire list. Which means you will get to know only 1st error that occurred and the entire transaction will fail. But if you are using 2nd method you can capture each of the record with it’s own error message and handle them differently. The Database.saveresults method will give you more robust Error handling opportunities.
Can we use Database.insert all the time? Well most of the time you can use it but except for few usages you cannot like JavaScript remoting doesn’t support this.
This article was written for insert operation but holds true for other types as well like update etc..
Hope this helps someone out there…..
Keep reading and sharing……
Leave a Reply