How to Get Id of Inserted Record via Apex [closed]

How can I get the Id of a record which has been inserted using Apex?

Answer

The platform allocates an ID value and sets it in an SObject’s ID field implicitly as part of the insert operation:

Account a  = new Account(Name = 'Acme');
// a.Id is null here

insert a;
// a.Id now has a value set by the platform

Fields are accessed using just a dot and the field name; there isn’t a corresponding getId() method. (The generic field get method does work for ‘Id’.)

So most of the time you do not assign a value to an object’s ID field. An exception is where you have the ID of the object (perhaps from a lookup field on a different object) and want to update the object. In that case you can assign the ID and so save having to first query the object:

Account a = new Account(Id = accountId, Name = 'New Name');
update a;

Attribution
Source : Link , Question Author : user13392 , Answer Author : Keith C

Leave a Comment