Reputation: 369
I've created a Symfony project using Doctrine, and when I persist an entity in the database, I see that it saves twice.
I have used both persistAndflush()
, and persist()
and flush()
separately, but I don't understand the problem.
Upvotes: 23
Views: 38535
Reputation: 61
The persist()
and persistFlush()
methods are used to save an entity to the database. Both methods are part of the EntityManager
interface, which is used to manage the persistence of entities in a Java application.
The main difference between persist()
and persistFlush()
is that persist()
queues the entity for insertion into the database, but does not immediately execute the insert statement. Instead, the insert is executed when the transaction is committed or when the flush()
method is called.
persistFlush()
, on the other hand, combines the persist()
and flush()
methods into a single call. It queues the entity for insertion and immediately executes the insert statement, flushing the changes to the database.
Both persist()
and persistFlush()
can be useful in different situations. persist()
can be useful when you want to queue multiple entities for insertion and flush them all to the database at once, while persistFlush()
can be useful when you want to immediately persist an entity and ensure that it is saved to the database.
In general, it's a good idea to use persist()
when you want to optimize for performance and persistFlush()
when you want to ensure that the entity is immediately persisted to the database.
Upvotes: 5
Reputation: 675
Imagine that in your controller you have more than one operation to do on different objects: $obj1
, $obj2
, $obj3
.
Now you need to save all the transformations (create, update, delete) in your database. To tell the ORM that it needs to do these operations, you need to "fill the queue" by:
$em->persist($obj1);
$em->persist($obj2);
$em->persist($obj3);
Now in your queue you have the three objects, but still no changes in database. The flush operation tell the ORM/ODM to "now apply the changes".
$em->flush();
So the modifications applied on your three objects will be stored in your database in the order of the persist call: $obj1
, $obj2
, $obj3
.
Upvotes: 41
Reputation: 172
In other words, between every 2 flush, a new transactions starts. You can compare this with the transaction, commit, rollback using normal PDO connecton
Upvotes: 10