An Entity Manager is a core component of ORM (Object-Relational Mapping) frameworks, especially in Java (JPA – Java Persistence API), but also in other languages like PHP (Doctrine ORM).
Persisting:
Finding/Loading:
Retrieves an object by its ID or other criteria.
Example: $entityManager->find(User::class, 1);
Updating:
Tracks changes to objects and writes them to the database (usually via flush()
).
Removing:
Deletes an object from the database.
Example: $entityManager->remove($user);
Managing Transactions:
Begins, commits, or rolls back transactions.
Handling Queries:
Executes custom queries, often using DQL (Doctrine Query Language) or JPQL.
The Entity Manager tracks the state of entities:
managed (being tracked),
detached (no longer tracked),
removed (marked for deletion),
new (not yet persisted).
$user = new User();
$user->setName('Max Mustermann');
$entityManager->persist($user); // Mark for saving
$entityManager->flush(); // Write to DB
The Entity Manager is the central component for working with database objects — creating, reading, updating, deleting. It abstracts SQL and provides a clean, object-oriented way to interact with your data layer.