原则2:交易不起作用

Code handled by my request (just testing purpose):

$em->beginTransaction();
try {
    $repository = $em->getRepository(User::class);
    /** @var User $entity */
    $entity = $repository->findOneBy(['user' => 1]);
    $em->lock($entity, LockMode::PESSIMISTIC_WRITE);
    // $em->refresh($entity); Would solve the problem. See edit at bottom.
    $entity->increase(1); // just an integer field will be increased

    sleep(2);

    $em->persist($entity);

    $em->flush();
    $em->commit();
} catch (\Exception $e) {
    $em->rollback();
    throw $e;
}

When I fire up two requests (handled by different Nginx children) following happens:

  1. Before requests: Number is 30
  2. Request 1 is fired
  3. Request 2 is fired
  4. Request 1 finished. Number is 31
  5. Request 2 finished. Number is 31

I expect 32 after finishing of the second request since there are write locks inside of a transaction set. Why does that not work?

Edit: I have to add $em->refresh($entity) to get it work. But I wonder if I have to do that manually every time.

It seems the solution with doing $em->refresh($entity) is the way to do it. I asked the Doctrine 2 developer.