Doctrine 2 Exception The EntityManager is closed

Doctrine 2’s EntityManager class will permanently close connections upon failed transactions. Thus, further requests using these closed instances will fail with the following exception:


The EntityManager is closed 原因是某个sql语句执行错误,导致entitymanager自动关闭。后续的数据库更新操作无法执行。

具体的sql执行错误可以查询日志:storage/logs/lumen-2020-xx-xx.log

比如: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null


Doctrine\\ORM\\ORMException' with message 'The EntityManager is closed.
So, make sure to check your EntityManager’s state before your actual tasks:
临时解决办法,在更新操作之前,先检查entitymanager的打开状态,如果被关闭,则重新打开,可以避免出现closed错误。

if (!$entityManager->isOpen()) {
  $entityManager = $entityManager->create(
    $entityManager->getConnection(), $entityManager->getConfiguration());
}
Better, create a function called getEntityManager that takes care of this check and makes sure that you always get a viable instance of EntityManager to work with:


private static function getEntityManager() {
  if (!self::$entityManager->isOpen()) {
    self::$entityManager = self::$entityManager->create(
      self::$entityManager->getConnection(), self::$entityManager->getConfiguration());
  }


  return self::$entityManager;
}
So you can use:


self::$entityManager = self::getEntityManager();
self::$entityManager->persist($some_entity_instance);
self::$entityManager->flush();
Thats’s it.

有话要说