Where Do Hibernate Transactions Fit In?

I recently got into a discussion on where Hibernate transactions should be placed in the scope of DAO logic. Some people have a desire to begin and end a transaction inside a DAO method. This is really a question of unit of work, and not scope of the DAO.

Let’s say we have a single unit of work that involves updates to several tables. Within the scope of this unit of work we have to update table 1, table 2 and table 3. During the sequence of events table 1 updates just fine and then table 2 fails to update. Now, are we to move on and update table 3? What are we to rollback? Do we want to rollback both changes (the partial change to table 2 and the complete change to table 1 that is within the same unit of work)? (We probably do.)

But with our transactions being committed within every single DAO method we cannot; The previous transaction was already committed before we discovered an error.  So the ultimate answer is this: Placing transaction begin and end statements within each DAO method makes things messy. While it is important to keep the length of a transaction as short as possible, it CANNOT be done at the expense of the integrity of a the unit of work!

In the example that I scribbled below (and its not a great example), a single unit of work (adding a person with an address and an employer) allows for partial completion. This isn’t what was desired in the first place.

[Stack OverFlow: DAO PAttern-Where to Transactions Fit In?]
[Java Bouique: Managing DAO Transactions in Java]