Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do DQL queries refresh entities already in the identity map?

Tags:

doctrine-orm

Say I load a user by id:

$user = $em->find('Domain\Model\User', 123);

And now run a DQL query to select several users, among them this already known user:

$users = $em->createQuery('SELECT u FROM Domain\Model\User u')->getResult();

If user 123 has changed in the database between these two queries (supposing I'm not inside a REPEATABLE READ transaction), will this query refresh user 123 with the fresh data returned by the query, or will it just return the object from the identity map while ignoring the new data?

like image 734
BenMorel Avatar asked Dec 12 '22 02:12

BenMorel


1 Answers

After testing this exact use case, it turns out that Doctrine 2 does not refresh an existing entity with the data returned by a DQL query, and only returns it as is from the identity map.

I finally found the relevant documentation confirming this:

In normal operation a result-set that loads data of an already existing entity is discarded in favor of the already existing entity.

It also gives a way to force the DQL query to refresh the entity, using Query::HINT_REFRESH:

If you specify this hint and a query returns the data for an entity that is already managed by the UnitOfWork, the fields of the existing entity will be refreshed.

Which is quite handy and easy to use:

use Doctrine\ORM\Query;

$users = $em->createQuery('SELECT u FROM Domain\Model\User u')
    ->setHint(Query::HINT_REFRESH, true)
    ->getResult();
like image 80
BenMorel Avatar answered May 29 '23 20:05

BenMorel