sajad torkamani

In a nutshell

The Unit of Work pattern is a technique for synchronizing changes to your in-memory object model (e.g., Java objects) with the database (e.g., MySQL).

What is the Unit of Work pattern?

Instead of changing the database with each change to your object model, you create a Unit of Work object to keep track of all the changes to your object model.

When you’re ready to commit the changes, the Unit of Work decides what to do and how to do it in the most efficient way. It opens a transaction, does any concurrency checking, and writes the changes.

This provides the following benefits:

  • Faster writes: you commit all the changes in a single database operation rather than multiple.
  • Consistency: combining multiple changes in a single transaction makes it easier to rollback all the changes if one fails. This helps avoid inconsistent state in your database.

Sources

Tagged: Patterns