Helloworlder's blog

How to change isolation level by using Doctrine 2

2021-06-15 doctrine, orm, php

Unfortunately, the only solution is to change the session's isolation level. We usually don't need to change it, though sometimes we do.

/** @var \Doctrine\ORM\EntityManager $entityManager */

$oldIsolationLevel = $entityManager->getConnection()->getTransactionIsolation();
$entityManager->getConnection()->setTransactionIsolation(\Doctrine\DBAL\TransactionIsolationLevel::SERIALIZABLE);
$entityManager->beginTransaction();
try {
    // do something...
    
    $entityManager->flush();
    $entityManager->commit();
} catch (\Exception $e) {
    $entityManager->rollback();
    throw $e;
} finally {
    $entityManager->getConnection()->setTransactionIsolation($oldIsolationLevel);
}