0

Below is my code which I'm executing in developer console.

Contact con = new Contact( LastName = 'JOHNSON', LeadSource = 'Web');
Savepoint sp = Database.setSavepoint();
insert con;
Database.rollback(sp);
con.LeadSource = 'Email';
system.debug('>>> Idd.. '+con);
Insert con;

After Savepoint, if I'm trying to insert the contact again, I'm getting INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id] error

In my debug log I can see the Contact Id but when I tried to see that record, the record was not available not even in Recycle bin.

If I cange my code like below

Contact con = new Contact( LastName = 'JOHNSON', LeadSource = 'Web');
Savepoint sp = Database.setSavepoint();
insert con;
Database.rollback(sp);
con.LeadSource = 'Email';
system.debug('>>> Idd.. '+con);
update con;

then I'm getting INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] error.

What I'm not able to understand is why Id of Contact record is available even after rollback.

Why I'm not able to insert/Update the same Contact after rollback.

1

Savepoint operates between database Save and Commit.

insert con; --- At this line, the record got Saved which would have created the Record ID but not committed to database.

Database.rollback(sp); - After rollback, commit got cancelled but still the record id is there in your local instance con.

You can try something like this to use the same instance after rollback. Reset the Id field to null and try the insert.

Contact con = new Contact( LastName = 'JOHNSON', LeadSource = 'Web');
Savepoint sp = Database.setSavepoint();
insert con;
Database.rollback(sp);
con.LeadSource = 'Email';  

con.id = null;

system.debug('>>> Idd.. '+con);
Insert con;
0

Based on the documents available here

The ID on an sObject inserted after setting a savepoint is not cleared after a rollback. Create an sObject to insert after a rollback. Attempting to insert the sObject using the variable created before the rollback fails because the sObject variable has an ID. Updating or upserting the sObject using the same variable also fails because the sObject is not in the database and, thus, cannot be updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.