Java Reference
In-Depth Information
TRANSACTION_NONE AND AUTOCOMMIT
The JDBC specification defines a fifth transaction mode, which is TRANSACTION_NONE. In
theory, this transaction mode cannot be specified via the setTransactionIsolation() mode,
since if a transaction already exists, its isolation level cannot be set to none. Some JDBC drivers
(notably for DB2) do allow that call to be made (and in fact even default to that mode). Other
JDBC drivers will allow an isolation level of none to be specified in the properties used to initial-
ize the driver.
In a strict sense, a statement executing from a connection with TRANSACTION_NONE se-
mantics cannot commit data to the database: it must be a read-only query. If data is written, there
must be some locking; otherwise, if one user is writing a long string to a table using
TRANSACTION_NONE semantics, a second user could see a partial string written in the table.
It's possible there are databases that operate in that mode, though that would be uncommon; at the
very least, data written to a single table is expected to be written atomically. Hence an operation
that writes will in reality have (at least) TRANSACTION_READ_UNCOMMITTED semantics.
A TRANSACTION_NONE query cannot be committed, but JDBC drivers that use
TRANSACTION_NONE may allow queries to be written if autocommit is enabled. This means
that the database is treating each query as a separate transaction. Even so, since the database is
(likely) not allowing other transactions to see partial writes,
TRANSACTION_READ_UNCOMMITTED semantics are really being used.
For simple JDBC programs, this is sufficient. More commonly—and particularly when used
with JPA—programs may want to mix isolation levels on data within a transaction. In an ap-
plication that queries my employee information so as to ultimately give me a large raise, ac-
cess to my employee record must be protected: that data needs to be treated as
TRANSACTION_REPEATABLE_READ. But that transaction is also likely to access data in
other tables, such as the table that holds my office ID. There is no real reason to lock that
data during the transaction, so access to that row could certainly operate as
TRANSACTION_READ_COMMITTED (or possibly even lower).
JPA allows you to specifying locking levels on a per-entity basis (and of course an entity is
[at least usually] simply a row in the database). Because getting these locking levels correct
can be quite difficult, it is easier to use JPA rather than performing the locking in JDBC
statements. Still, it is possible to use different locking levels in JDBC applications, employ-
ing the same pessimistic and optimistic locking semantics that JPA uses (and if you're not fa-
miliar with those semantics, this example should serve as a good introduction to them).
Search WWH ::




Custom Search