Java Reference
In-Depth Information
@Stateless
public
public class
Calculator {
@PersistenceContext ( unitName = "Calc" )
EntityManager em ;
class Calculator
public
public void
void calculate () {
UserTransaction ut = ... lookup UT in application server ...;
ut . begin ();
Parameters p = em . find (...);
ut . commit ();
... perform expensive calculation ...
ut . begin ();
em . persist (... answer ...);
ut . commit ();
}
}
Splitting the transaction—which can only be done easily with user-managed transac-
tions—limits the effect of the transaction on the scaling of the application. Strictly speaking,
this could have been done with container-managed transactions by splitting the work into
three different methods, each with a different transaction attribute. In general, the UMT ap-
proach is far more convenient.
Similarly, a servlet using user-managed transactions can establish a transaction boundary that
spans multiple calls to an EJB. Using container-managed transactions to accomplish the
same thing means adding into the EJB interface a new metamethod that calls those other
methods within the same transaction.
In a Java SE application, the entity manager is responsible for providing the transaction ob-
ject, but the application is responsible for demarcating the transaction boundaries on that ob-
ject. The JPA example to populate the database of stock prices includes the following code:
public
public void
void run () {
for
for ( int
int i = startStock ; i < numStocks ; i ++) {
EntityManager em = emf . createEntityManager ();
EntityTransaction txn = em . getTransaction ();
txn . begin ();
while
while (! curDate . after ( endDate )) {
StockPrice sp = createRandomStock ( curDate );
iif ( sp != null
null ) {
em . persist ( sp );
for
for ( int
int j = 0 ; j < 5 ; j ++) {
StockOptionPriceImpl sop =
Search WWH ::




Custom Search