Magento 2 – use transaction to save objects
In Magento 2 you can use transaction to save objects. This is a less known feature that is helpful, if you want to guarantee a valid state in your database. You can combine many objects to save with a single transaction. This transaction commits or can be rolled back if an error happened.
Magento 2 – use transaction to save objects
The following simple code demonstrates on how to use transactions in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class MyClass { protected $saveTransaction; public function __construct \Magento\Framework\DB\TransactionFactory $transactionFactory ){ $this->saveTransaction = $transactionFactory->create(); } public function saveManyObjects() { ... $this->saveTransaction->addObject($order); $this->saveTransaction->addObject($customer); $this->saveTransaction->addObject($customObject); $this->saveTransaction->save(); } } |
If you run saveManyObjects() method of this class, all given objects are saved at once. For a transaction you need to inject \Magento\Framework\DB\TransactionFactory, which offers all needed functionality. You can add objects to save by addObject() method. You can add all methods: orders, customers, products or even custom objects. save() does an automatically commit or rollback for you.
Custom SQL statement transactions
Sometimes you may want to create your own SQL statements and also want to use transactions. For this you can use the following sample code:
1 2 3 4 5 6 7 8 9 | $connection = $this->getConnection(); $connection->beginTransaction(); try { ... $connection->commit(); } catch (\Exception $e) { $connection->rollBack(); throw $e; } |
You can call beginTransaction() to initialize a transaction on you connection object. You can then create your insert or update statements. With commit() you will push it to database. If something went wrong, your try catch will call a transaction rollBack() to restore a consistent database state and throws that error.
Performance
Initially I searched for transactions to speed up a product import. If you sum up all your objects to save them at once in one single transaction, it is actually faster. The problem, it is only faster by a little percentage of total run time. It does not speed up your product saving as often needed!
Conclusion
A Transaction is a useful tool to make database changes safe. It prevents you from destroying a database if something went wrong. Magento 2 offers you all you need to use transactions, but this feature is less known and often not used. Why?