"Go" JDBC Transaction processing

Source: Internet
Author: User
Tags stmt

http://apzx2007.blog.163.com/blog/static/70507440200910236014880/

In JDBC database operations, a transaction is an inseparable unit of work consisting of one or more expressions. We end the transaction by committing a commit () or fallback rollback (). The methods for transactional operations are located in interface java.sql.Connection.

First of all, we should note that in JDBC, transaction operations are automatically committed by default. In other words, an updated expression on the database represents a transactional operation. After the operation succeeds, the system will automatically call commit () to commit, or rollback () will be called back and forth.

Second, in JDBC, you can suppress autocommit by calling Setautocommit (false). You can then use the expressions of multiple database operations as a single transaction, and commit () to commit as a whole after the operation is complete. If one of the expression operations fails, it does not execute to commit () and will produce a response exception. At this point, you can call rollback () for fallback when the exception is captured. Doing so can maintain the consistency of the relevant data after several updates. The sample code is as follows:

Java code
try {

conn = Drivermanager.getconnection ("jdbc:microsoft:sqlserver://localhost:1433; USER=JAVADB; Password=javadb;databasename=northwind);

Click Disable Auto-commit, set fallback

Conn.setautocommit (FALSE);

stmt = Conn.createstatement ();

Database Update Operations 1

Stmt.executeupdate ("Update firsttable Set name= ' testtransaction ' Where ID = 1");

Database Update Operations 2

Stmt.executeupdate ("insert into firsttable ID = 12,name = ' TestTransaction2 '");

Transaction commit

Conn.commit ();

}

catch (Exception ex) {

Ex.printstacktrace ();

try {

The operation is not successful and is rolled back

Conn.rollback ();

}

catch (Exception e) {

E.printstacktrace ();

}

}


In this case, the execution of the above program, or two operations are successful, or two are unsuccessful, the reader can modify the second operation to make it fail, so as to check the effect of transaction processing. We also mentioned the level of isolation that JDBC supports for the firm, which is discussed in more detail below.

The JDBC API supports transaction locking of the database and provides 5 operations support and 2 lock densities.

5 Kinds of lock support for:

static int transaction_none = 0;

static int transaction_read_uncommitted = 1;

static int transaction_read_committed = 2;

static int transaction_repeatable_read = 4;

static int transaction_serializable = 8;

The specific instructions are shown in table 4-2.

2 Kinds of lock density:

The last item is locked for the table and the remaining four lines are locked.

"Dirty" Data Read and write (Dirty Reads): When one transaction modifies the value of a row of data and does not commit, another transaction reads the row value. If the previous transaction has a fallback, the latter transaction will get an invalid value ("dirty" data).

Repeat read and write (repeatable Reads): When a transaction reads a row of data, the other transaction modifies the data row at the same time. The previous transaction will get an inconsistent value when it reads the row repeatedly.

Error (image) Read and write (Phantom Reads): When a transaction makes a data query in a table, another transaction is inserted into the data row that satisfies the query criteria. The previous transaction will get an additional "image" value when it reads the value that satisfies the condition repeatedly. JDBC sets transaction support and locks on the basis of the default values provided by the database, and can, of course, be set manually:

Settransactionisolation (transaction_read_uncommitted);

You can view the current settings for the database:

Gettransactionisolation ()

It is important to note that the database and its drivers must support the appropriate transaction operation before the manual setting is performed.

The above setting increases with the value, its transaction independence increases, can effectively prevent the conflict between transaction operations, but also increases the overhead of locking, reduces the concurrency of accessing database between users, and the running efficiency of the program decreases. The conflict between the efficiency of the program and the consistency of data is therefore balanced. In general, for queries involving only the database, you can use the Transaction_read_uncommitted method, and for data queries far more than the updated operation, you can use transaction_read_committed mode , for more updates, you can use transaction_repeatable_read; in the case of higher data consistency, consider the last item, because it involves the table lock, so it will have a great impact on the efficiency of the program operation.

In addition, the default value of database driven transactions in Oracle is Transaction_none, that is, transactional operations are not supported, so you need to set them up manually in your program. In short, JDBC provides a relatively complete support for database transaction operations, and transaction operations can improve the efficiency of the program and maintain data consistency.

4.8.4 Distributed Transaction Processing

For the most part of this section, the transaction that we have been discussing has been a single connection that involves only one database, and the following is a brief introduction to distributed transactions.

A transaction is a request for a service, and accepting or rejecting such a request will immediately reply to the requestor. Between requests and responses, resources (such as files, databases, and so on) are read and updated as needed. From the development history of transaction processing, it has undergone an evolutionary process from centralized processing to distributed processing. This shift is driven primarily by the rise of the internet, the likelihood of a customer's objective need for faster, more secure transaction processing, and the technical implementation offered by object-oriented applications.

In the Internet environment, distributed transaction processing needs to be further expanded in order to meet the challenges of increasing business throughput, and must support the interoperability of decentralized application components, which must be implemented in a distributed transaction management manager. This is different from the traditional centralized transaction processing of the most distinctive features. Specifying a transaction is called Transaction demarcation (demarcation), which is a way to mark a set of operations that make up a transaction by binding a distributed component to a global transaction to complete the transaction demarcation.

The most commonly defined approach is the thread that performs the operation for the transaction token, which is called programmatic demarcation. Such a transaction can be suspended by removing the token and resuming execution at a later time by explicitly passing the transaction context from the hanging point to the recovery point. Transaction demarcation ends after a commit or a fallback request to the transaction manager, which instructs all participating resource managers to permanently record the effect of the operation in the transaction, and the fallback request causes the resource manager to undo the effect of all operations in the transaction.

An alternative programming definition is the definition of a statement. Component-based transaction processing systems such as Microsoft transactional servers, and application server-based transaction processing systems such as the Enterprise Java Beans specification support declarative scoping. In this technique, artifacts are marked as transactional at deployment time. This implies two things. First, the defined responsibilities are transferred from the application to the container (Container) that holds the components. For this reason, this technique is also called management container definition. Second, the definition is extended from the time of application construction (static) to the component deployment period (dynamic).

Because multiple application artifacts and resources participate in a transaction, it is necessary for the transaction manager to establish and maintain the state of the transaction that occurs. This is usually done in the form of a transaction context. A transaction context is an association (association) between a transactional operation on a resource and a component that invokes an operation. During a transaction execution, all the threads participating in the transaction share the transaction context. So the transaction context logically encapsulates (Envelop) all operations performed on a transactional resource during a transaction. Transaction contexts are typically maintained transparently by the underlying transaction manager. The details of the discussion of distributed transactions are beyond the scope of this book, and the purpose here is to give you some ideas and concepts. Here are the technical models for distributed transaction processing:

1. X/open Distributed Transaction Processing model

X/open Distributed Transaction Processing (DTP) model is a distributed processing model proposed by open Group, and Open Group is a consortium of vendors. This model is a standard among most commercial vendors in the field of transactional processing and databases. The model consists of four components:

(1) Application: Implementing Transactional operations

(2) Resource Manager: Same as above discussion

(3) Transaction manager: Same as above discussion

(4) Communication Resource Manager: facilitates interoperability between different transaction managers in different transaction processing domains

X/open DTP models are established in the industry. Some business affairs management products, such as Txseries/encina (products that are fully affiliated with IBM Tranarc), Tuxedo and topend (BEA Systems Products), and at/T GIS support TX interfaces. Although Microsoft's Transaction Server does not support the TX interface, it is able to interoperate with XA-compliant databases such as Oracle. Similarly, most commercial databases like Oracle,sybase,informix and Microsoft SQL Server, as well as messaging middleware products such as IBM MQSeries, and Microsoft MSMQ Server provide an implementation of the XA interface.

2. OMG Object Transaction Service

The Object Transaction Service (OTS) is a distributed transaction service defined by the Object Management Organization (OMG). This specification extends the CORBA model and defines a series of interfaces that complete transaction processing across multiple CORBA objects (across). The OTS model is based on the X/open DTP model and provides enhancements, such as the OTS model, which replaces the XA and TX interfaces in the function form with the CORBA IDL interface, in which various objects in this model are tuned for communication via CORBA methods above the IIOP.

The OTS system consists of the following components:

Transactional client: A program or object that invokes an operation on a transactional object.

Transactional object: A CORBA object that encapsulates (encapsulate) or references (refers to) persistent data, and its behavior relies on the operation of whether it is invoked during a transaction.

Recoverable objects: A transactional object that directly maintains persistent data and participates in transactional protocols.

Transactional server: A collection of one or more transactional objects (collection).

Recoverable server: A collection of objects, at least one of which is recoverable.

Resource object: A Resource object is an object in the transaction service that is registered to participate in a two-phase commit and recovery protocol.

"Go" JDBC Transaction processing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.