Java Reference
In-Depth Information
EJB manages transactions either programmatically or via annotations. This will be covered
in subsequent sections. When managing transactions programmatically—that is, bean-
managed persistence—you're using APIs defined by JTA. Within the EJB container, con-
nections to resources such as databases are provided via DataSource , and very often
these DataSource s support the XA protocol. The XA protocol enables transactions to
span multiple resources such as databases and containers. DataSource s are retrieved
via JNDI either programmatically or via the @Inject annotation. Optionally, you can
use JPA to shuttle your data between the database and Java objects—JPA will use the
DataSource under the hood and participate in transactions configured by EJB. The
transaction manager implements the JTS interface and provides the implementation of JTA.
Configuration of isolation levels isn't specified by the Java EE standard and is thus
container-specific. Generally, isolation levels are configured when defining the
DataSource . As a result, the isolation level is global and affects all connections and
transactions. Although it's possible to programmatically change the isolation level on a
connection acquired from a DataSource , this is dangerous. First, if this connection ends
up back in the pool without its original setting, it'll impact other transactions. Second,
countermanding configuration settings from the container obfuscates application behavior.
If you're limited to setting the transaction isolation level on the DataSource , which
isolation level should you choose? The read uncommitted is dangerous because you'd see
changes from other transactions that haven't been committed and aren't necessarily valid.
This could cause unexpected rollbacks and leave the database in a contorted state. Repeat-
able read suffers from phantom reads—for instance, a query when executed twice returns
different results due to changes made by other transactions. Serializable, on the other hand,
scales poorly because locks must be acquired on the data. For situations where read com-
mitted isn't acceptable, there are several approaches. One is to create a data source for each
isolation level you need. Another approach is to use version columns and optimistic lock-
ing.
6.1.4. When to use transactions
Transactions are an integral part of EJB. By default, EJBs will use CMTs and the bean will
either participate in an existing transaction, if already started, or start a new transaction.
This is the behavior of EJBs if you don't provide any additional configuration. As you've
seen, transactions are extremely important for ensuring data integrity. The more apt ques-
tion is this: when would you not want to use transactions? You wouldn't use transactions
Search WWH ::




Custom Search