views:

64

answers:

3

Hey everybody.

According Martin Fowler's Unit of Work description:

"Maintains a list of objects that are affected by a business transaction and coordinates the writing out of changes and resolution of concurrency problems."

Avoiding

very small calls to the database, which ends up being very slow

I'm wondering. If we just delimit it to database transaction management, won't prepare statements help with this?

A: 

Prepared statements have nothing at all to do with transactions.

What Fowler is referring to is network latency: If you go back and forth to the database, you'll incur a network delay every time.

This question has two ideas confounded together: transactions and batches. Batching multiple database operations together and sending them all to the database to be processed can address what Fowler is talking about, too.

Which one do you really care about here?

duffymo
+1  A: 

A good data access layer implementation will do this for you. For example, Hibernate/NHibernate can defer flushing changes until the end of the transaction, or when you explicitly request changes to be flushed. Alternatively, you can fetch the data in one transaction and store changes in another, using optimistic locking. This avoids long database transactions.

If you're rolling your own access layer you can add batching to the JDBC connection to reduce the latency overhead of many small update/insert requests. Even so, I think this pattern is a good idea, since it gives a good overview of all the changes in one place. So you can then submit all your changes at once, quickly in a database transaction, rather than having writes to the db spread out over the duration of the business transaction - which could be a long time, and long long db transactions are generally not a good idea.

PreparedStatements are orthoganal to this pattern - they neither directly help or hinder. The pattern is about reducing network latency and having short transactions, as well as having an overview of all entity changes in a business operation.

mdma
A: 

The pattern is more general than just databases. Whenever you can bundle several small operations into one, the Unit of Work pattern might be applicable.

As an example, think of an AJAX app, where you want to notify the server of certain operations you have performed on the client. You might want to bundle those operations into a single larger operation. The server may or may not pass the data on to a database.

On the server side, a unit of work might have to save data in the database and push it to another client working with the same data.

The key thing to note is that a "business transaction" and a DB transaction are two different things.

Jørgen Fogh