Java Reference
In-Depth Information
} finally {
if (session != null) session.close();
if (conn != null) conn.close();
The code isn't as elegant this way, which is sometimes a good reason to write your
own transaction manager. Furthermore, you should still define a transaction man-
ager of type EXTERNAL and also provide at least a SIMPLE DataSource ; otherwise
certain features such as lazy loading will not work properly.
Avoid using this approach if possible, and always consider writing your own
transaction manager.
7.6 Demarcating transactions
Now that you know how to start and end transactions in various ways, you might
be asking yourself, “Where should I start and end my transaction?” As it turns out,
this question of where can be harder to answer than the question of how. As with
most difficult questions, the answer is: “It depends.” You'll find a lot of different
answers depending on whom you ask.
Where you demarcate your transaction will determine how long the transac-
tion remains open, as well as how much work is included within the scope of the
transaction. Knowing this, it is obvious that performance will suffer with longer-
lived, wider-scoped transactions. However, these larger transactions are also some-
what safer in that they ensure the integrity of what is probably a group of related
work (otherwise, why would it all be taking place within a single request?).
Because it can be difficult to make the decision, here is a simple rule of thumb:
The scope of a transaction should be as wide as possible, but should not extend
beyond the scope of a single user action.
For example, in a web application, when a user clicks a button to submit a form,
the transaction scope should begin immediately, but by the time the response
page is rendered in the user's browser, the transaction should be complete. In a
rich client application, the rule is generally the same. A transaction should
include all of the work involved in a single user operation—which is generally rep-
resented by a single button click. Another way to think about it is this: a user
should never be able to walk away from their computer and leave a transaction
open, or incomplete.
Search WWH ::

Custom Search