Q:

How can I update an entity where $id is NOT autogenerated in Doctrine (Symfony 4)?

My Symfony 4 entity has a non-autoincrement ID:
/**
 * @ORM\Entity(repositoryClass="App\Repository\PropertyRepository")
 */
class Property
{
    /**
     * @ORM\Id()
     * @ORM\Column(type="integer")
     */
    protected $id;

    .....

    public function setId($id): self
    {
        $this->id = $id;
        return $this;
    }

I use the setId() method to set it myself.
$prop = new Property();
$prop->setId(1);
$prop->setName('baobao');
$this->em->persist($dbProperty);
$this->em->flush();

I've no problem on INSERT, but if I run the same code twice if fails:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'PRIMARY'
The second query is an INSERT too, even if I was expecting an UPDATE.

A:

@Florian Hermann comment pointed m in the right direction. As show here https://symfony.com/doc/current/doctrine.html#updating-an-object it's required to load the object first:
$propertyRepository = $this->em->getRepository(Property::class);

$dbProperty = $propertyRepository->find($id);

if(empty($dbProperty)) {

    $dbProperty = new Property();

} else {

    $dbProperty->setId($id);
}

$dbProperty->set....
$dbProperty->set....
$dbProperty->set...
$this->em->persist($dbProperty);

$this->em->flush();

