TLDR
- Doctrine ORM 3.0 throws if you pass a class name to EntityManager::clear(), and flush($entity) now flushes everything.
- Decide what each partial clear was for, then pick a full clear, a manual detach, a separate entity manager, or DBAL writes.
- If shared code must run on ORM 2 and 3, branch on what the installed code supports (parameter counts, types, classes), and watch for decorators.
- Most of the upgrade effort showed up in tests, where ORM 3's typed return values broke loose mocks.
If your Symfony batch jobs call $entityManager->clear(SomeEntity::class) to keep memory in check, Doctrine ORM 3 will break them. ORM 3.0 removed partial clearing: passing any argument to EntityManager::clear() now throws an exception, and flush($entity) quietly became a full flush(). The fix is not a find-and-replace. You have to decide what "clear only these objects" really meant in each job, replace it with something explicit, and, if your code is shared, make it work on both ORM 2 and ORM 3 by checking what the installed version can do instead of guessing from version numbers.
We worked through this in November 2026 while preparing a shared integration library for ORM 3. This post covers what broke, the options we weighed, the one we picked and its risks, and a checklist you can reuse.
How we know, and the limits
How we know: This is based on our own commit history from November 19, 2026, when Willem Luijt added ORM 3 compatibility to a shared Symfony library that several of our ecommerce integration projects depend on. Those projects run long console commands that sync products, inventory, locations and orders between systems. Every Doctrine behavior described here was checked against the Doctrine ORM 3.0 upgrade notes and source code on the day of publishing (links at the end).
Limits: We are describing one library and the patterns it used. We did not benchmark memory before and after, so this post makes no claims about memory savings. Your entity graph, cascade settings and job design may make our chosen approach unsafe for you; the tradeoffs section explains when.
What changed in Doctrine ORM 3
The Doctrine ORM 3.0 upgrade notes list two breaks that matter for batch work:
No more partial clear. "Passing an argument other than
nulltoEntityManager::clear()will raise an exception."UnitOfWork::clear()now always clears everything, andEntityRepository::clear()is gone.No more partial flush.
flush()no longer accepts an entity or array of entities. Change tracking now runs on every managed entity.
Doctrine's reason is stated plainly in the 2.x deprecation notes: partial clears and partial flushes caused data integrity problems in the managed entity graph and kept producing edge-case bugs. That reasoning is worth taking seriously before you rebuild the old behavior by hand, which is what most workarounds do.
The same release also removed ClassMetadataInfo (use ClassMetadata), added native types to many method signatures, and replaced array field mappings with FieldMapping objects. Those mostly show up in tests and in classes that extend Doctrine's own classes, which we cover below.
Why a long-running job clears only one entity class
Doctrine keeps every entity it loads or persists in its identity map until you clear it. In a short web request that is fine. In a console command that loops over a large catalog or order history, the identity map grows for the whole run. Doctrine's own batch processing guide recommends the classic pattern: persist, flush() every N items, then clear().
Our library had a narrower version of that pattern. Its data store flushes every 20 loop iterations, and its task logger writes a log row to the database for each log call (flushing occasionally and at the end of each run). After each flush, both cleared only the log entities:
$this->getObjectManager()->flush();
$this->getObjectManager()->clear(LogInterface::class);The intent was simple. Log rows are written once and never touched again by the job, so there is no reason to keep them in memory. Everything else stays managed, because the job may still be holding references to products, locations or orders it loaded earlier in the run. A full clear() would detach those too, and the next flush would silently skip changes made to them.
On ORM 3 that second line throws. Since it ran inside the logger, an upgrade without a fix would have turned every logged message into a failure point.
The options we weighed
There are four reasonable ways to replace a partial clear. None of them is free.
Switch to a full clear(). This is Doctrine's recommended path, and it is the right one if your job reloads what it needs after each batch. It was wrong for us without a larger refactor, because jobs across several projects hold entity references across batches.
Detach the matching objects yourself. Walk the unit of work's identity map and call
detach()on every entity of the target class.detach()still exists in ORM 3. This keeps the old behavior with the smallest code change.Give logs their own entity manager. A second entity manager for log writes can be cleared fully without touching the job's working set. Cleaner in theory, but it means more connections and more service wiring in every consuming project.
Write logs with DBAL instead of the ORM. Logs are append-only rows, so they do not really need entity tracking. This is probably the best long-term answer, and also the biggest change.
We chose option 2 for now, wrapped in a single helper so we can swap it out later without touching every caller. Our opinion: for append-only rows like logs and audit records, option 4 is where most teams should end up. Option 2 is a good bridge when you need ORM 3 compatibility without rewriting job logic at the same time.
The helper: check capability, not version
The library has to run on ORM 2 in older projects and ORM 3 in newer ones, so the helper asks the installed code what it supports. Here is a simplified version of what we shipped:
protected function clearObjectsOfClass(ObjectManager $om, string $className): void
{
// ORM 2: clear() still accepts a class name, so use it.
$clear = new \ReflectionMethod($om, 'clear');
if ($clear->getNumberOfParameters() >= 1) {
$om->clear($className);
return;
}
// ORM 3: detach matching entities from the identity map.
if (!method_exists($om, 'getUnitOfWork')) {
return;
}
$identityMap = $om->getUnitOfWork()->getIdentityMap();
foreach ($identityMap as $class => $entities) {
if (!is_a($class, $className, true)) {
continue;
}
foreach ($entities as $entity) {
$om->detach($entity);
}
}
}Three details took more thought than the main loop:
Decorators hide the real signature. Many Symfony apps wrap the entity manager in a decorator. On ORM 2 the decorator's
clear()signature may not tell you what the wrapped entity manager supports, so our full version checks whether the object is anEntityManagerDecoratorand, if the underlyingEntityManagerstill accepts a class name, calls the helper on the wrapped instance.The identity map is keyed by root entity class. In ORM 3's
UnitOfWork, entities are stored under their root entity name, not their concrete class. If your log entity sits in an inheritance tree, theis_a()check runs against the root. Make sure the class or interface you match on is implemented at that level.Mocks may not have a unit of work. In unit tests, an uninitialized entity manager mock can throw when you ask for its unit of work. Willem added a guard that catches that and returns quietly, which kept existing tests from needing new setup.
Checking capability instead of version will not protect you from every future change, but it fails in a readable way: if a later release changes clear() again, the reflection check tells you exactly which branch ran.
Overriding methods whose signatures changed
Partial clear was the visible break. The quieter one was method signatures. The library extends Doctrine's EntityManagerDecorator to remap getRepository() for extended resource classes. In ORM 2 that method is untyped. In ORM 3 it is getRepository(string $className): EntityRepository. PHP will not let one class declaration satisfy both.
The fix was to keep the shared logic in one trait and pick a thin signature trait at load time:
$method = new \ReflectionMethod(EntityManagerDecorator::class, 'getRepository');
$param = $method->getParameters()[0] ?? null;
if ($param && $param->hasType()) {
trait GetRepositoryCompatTrait { use GetRepositoryForOrm3; }
} else {
trait GetRepositoryCompatTrait { use GetRepositoryForOrm2; }
}Each version-specific trait declares only the public method with the right signature and calls the shared doGetRepository(). Conditional declarations like this look unusual, but they keep every real line of logic in one place. When ORM 2 support is dropped, you delete one file and one branch.
Partial flush: look for what else gets written
The flush($entity) change does not throw in ORM 3; the argument is just ignored. That makes it easy to miss. We found one call in a location verification step that persisted a location and flushed only that location. On ORM 3 the same line flushes every pending change in the unit of work.
The code change is one line, flush($location) to flush(). The review work is the important part: for each call, ask what else could be pending at that moment and whether writing it early is acceptable. In our case nothing else was pending in that step, so the change was safe. In jobs that stage many changes before a final commit, it might not be.
Expect your tests to break before your code does
Most of the November 19 commits touched tests, not production code. Typed returns in ORM 3 break mocks that used to cut corners:
A query builder mock that returned itself from
getQuery()fails, because ORM 3 types that method as returningQuery. The test now builds a realQuerymock, and picksAbstractQueryorQueryby reading the return type with reflection.Test helpers that built
ClassMetadataInfomocks needed a fallback toClassMetadata.Inherited field mappings passed as arrays now go through
FieldMapping::fromMappingArray()when that class exists.Metadata factory mocks had to target ORM's own
ClassMetadataFactory, sincegetMetadataFactory()is now typed to it.Repository mocks became stricter, so methods that concrete repositories expose under ORM 3 (like
createQueryBuilder()and a couple of log summary methods) had to be stubbed.
If your test suite leans on loosely typed Doctrine mocks, budget real time for this. It is the part of the upgrade that is hardest to estimate up front.
When this approach does not fit
If the entities you want to drop have associations with cascade settings, or other managed entities point at them, detaching by hand can leave the graph in exactly the inconsistent state Doctrine warned about. Use a full
clear()with reloading, or move those writes off the ORM.If you control every consuming project, skip dual support. Upgrade them together and use the clean ORM 3 pattern.
If your batch jobs are short and memory is not an issue, the simplest fix is to delete the partial clear and move on.
A checklist for your own ORM 3 upgrade
Search for
->clear(with an argument and->flush(with an argument across your code and your shared packages.For each partial clear, write down why it existed. Pick full clear, manual detach, a separate entity manager or DBAL based on that reason, not convenience.
For each partial flush, check what else could be pending at that point.
Put any workaround in one helper so you can replace it later.
If you must support ORM 2 and 3, branch on capabilities (parameter counts, parameter types, class existence) and account for decorators.
Find classes that extend Doctrine classes and compare overridden method signatures.
Run the test suite on both versions and fix mocks to match ORM 3 return types.
Widen your Composer constraints (for us,
doctrine/persistenceto allow 4.x) only after both versions pass.
If you have Symfony integrations or batch jobs that need to move to newer Doctrine and Symfony versions without a rewrite, our Symfony development team does this kind of upgrade work. Related reading: queue-aware batching with Symfony Messenger and upgrading Symfony 4.4 with Sonata Admin to 7.4.
Sources
Doctrine ORM UPGRADE.md, tag 3.0.0 (partial clear and partial flush removal, ClassMetadataInfo removal, 2.x deprecation reasoning). Accessed November 24, 2026.
Doctrine ORM documentation: Batch Processing. Accessed November 24, 2026.
Doctrine ORM 3.0.0 UnitOfWork source (identity map keyed by root entity name;
clear()anddetach()). Accessed November 24, 2026.
Last reviewed: November 24, 2026.
