Implementation of database transaction processing in Java

Source: Internet
Author: User
Tags commit error handling execution interface rollback thread
Transaction Processing | data | Database Summary This paper introduces the method of transaction processing in Java, and explains how to implement the JDBC transaction, JTA (Java Transaction API) transaction supported by the JavaBean and EJB components by using the example.





keywords JAVABEAN,EJB, database, transaction processing, JTA





JavaBean





JavaBean is a platform-independent component written in the Java language. It is a software component model that describes Java, somewhat similar to the concept of a Microsoft COM component. In the Java model, you can extend the functionality of the Java program infinitely by JavaBean, and you can quickly generate new applications through the combination of JavaBean. JavaBean can realize the reuse of code, and it has great significance for the maintainability of the program. Non-visual JavaBean, in the JSP program commonly used to encapsulate transaction logic, database operations, can be very good to achieve business logic and the separation of the foreground program. JavaBean has shown more and more vitality in the application of server side.





EJB





EJB Technology defines a reusable set of components: Enterprise JavaBeans. You can use these components to build your distributed application like a building block. When you write the code, the components are grouped into specific files. Each file has one or more enterprise Beans, plus some configuration parameters. Finally, these enterprise beans are configured on a platform loaded with EJB containers. Customers can navigate to a beans through these beans home interfaces and produce an instance of this beans. This allows the customer to invoke the beans application method and the remote interface. EJB Technology simplifies the development, configuration, and execution of enterprise application systems written in the Java language. There are three types of enterprise beans:session beans, entity beans and message-driven beans.





Transaction Processing





Information is an important asset of any enterprise, any business sector contains the inflow and outflow of information, and any enterprise department controls some information. At the same time, information must be disseminated to those in need at the right time. Furthermore, the information requires security constraints, and access control is generally implemented based on the type and content of the information. The database management system (DBMS) must provide a unified data protection function in order to ensure the security, validity and reliability of the data.





transaction is one of the core concepts in modern database theory. If a set of processing steps or all occur or one step is not performed, we call the group processing step as a transaction. When all the steps are executed as if they were an operation, we call the transaction committed. The transaction must be rolled back (back to its original system state) because of a partial or multi-step failure that causes no steps to be committed. Transactions must conform to the acid principles set out in ISO/IEC. Acid is an abbreviation for atomicity (atomicity), consistency (consistency), isolation (isolation), and persistence (durability). The atomicity of a transaction indicates that any failure in the execution of a transaction will invalidate any modifications made by the firm. Consistency indicates that all data affected by the transaction should revert to the state before the transaction was executed when the transaction execution failed. Isolation represents a modification of the data during the execution of a transaction and is not visible to other transactions until the transaction is committed. Persistence indicates that committed data should be in the correct state when a transaction fails to execute.





below We enumerate an example of transaction processing using a SQL Server database. The main table is a rules and regulations information table (bylaw), the main fields are record number, title, author, writing date, and so on. The two child tables are the attachment table (Bylaw_affix) and the Text information table (bylaw_content) respectively. The table structure is shown in Figure 1. The record number of the bylaw table corresponds to the record number of the Bylaw_affix table and the record number of the Bylaw_content table, and the operation of the rules and regulations information each time is the joint operation of the three tables. For example, to delete a record in the rules and regulations, if you do not use a transaction, you may have a situation where the database suddenly appears unexpectedly after the deletion of the first table, and the operation in table second to third does not complete so that the deletion does not complete or even destroys the data in the database. To avoid this, you should use a transaction that either succeeds or fails for all three tables. In other words, just keep the data consistent. Therefore, in order to ensure the integrity and consistency of data operations, in the design process to fully consider the issue of transaction processing.








Figure 1 Sample Table Structure




Transaction processing in
Java





Generally, the Java application Server supports JDBC transactions, JTA (Java Transaction API) transactions, container management transactions. In general, it is best not to use the above three transaction types in your program, such as nested JDBC transactions in JTA transactions. Second, the transaction should be completed in as short a time as possible, and not be implemented in different ways. Below we list two kinds of transaction processing methods.





1, javabean transaction processing using JDBC Method




How does
combine multiple SQL statements into one transaction in JDBC? In JDBC, when you open a Connection object connection, the default is Auto-commit mode, and each SQL statement is treated as a transaction, that is, each execution of a statement automatically gets the transaction confirmation. In order to be able to combine multiple SQL statements into one transaction, the Auto-commit mode is shielded. After the Auto-commit mode is masked, the SQL statement does not get a transaction acknowledgement if the commit () method is not invoked. All SQL after the most recent commit () method call is acknowledged at the method commit () call.





public int Delete (int sID) {


DBC = new DatabaseConnection ();


Connection con = dbc.getconnection ();


try {


Con.setautocommit (FALSE)//change default submission for JDBC transactions


dbc.executeupdate ("Delete from bylaw where id=" + SID);


dbc.executeupdate ("Delete from bylaw _content where id=" + SID);


Dbc.executeupdate ("Delete from bylaw _affix where bylawid=" + SID);


con.commit ()//submit JDBC Transaction


Con.setautocommit (TRUE);//restore default submission for JDBC transactions


Dbc.close ();


return 1;


 }


catch (Exception exc) {


con.rollback ()//rollback JDBC Transaction


Exc.printstacktrace ();


Dbc.close ();


return-1;


 }


}





2, Sessionbean in the JTA transaction





JTA is the Java Solution for transactional services. In essence, it is part of the Java EE model that describes the transaction interface (such as the UserTransaction interface, where the developer uses the interface directly or through the Java-EE container to ensure that the business logic can run reliably). The JTA has three main interfaces, namely the UserTransaction interface, the TransactionManager interface, and the Transaction interface. These interfaces share common transaction operations, such as commit () and rollback (), but also contain special transaction operations, such as suspend (), resume (), and Enlist (), which only appear on specific interfaces to allow some degree of access control in the implementation. For example, UserTransaction can perform transaction partitioning and basic transaction operations, while TransactionManager can perform context management.





The application can call the Usertransaction.begin () method to begin a transaction that is associated with the current line threads relative the application is running in. The underlying transaction manager actually handles the association between threads and transactions. The Usertransaction.commit () method terminates the transaction associated with the current thread. The Usertransaction.rollback () method discards the current transaction associated with the current thread.





public int Delete (int sID) {


databaseconnection DBC = null;


DBC = new DatabaseConnection ();


dbc.getconnection ();


usertransaction transaction = sessioncontext.getusertransaction ()//Get JTA transaction


try {


Transaction.begin (); Start JTA Transaction


dbc.executeupdate ("Delete from bylaw where id=" + SID);


dbc.executeupdate ("Delete from bylaw _content where id=" + SID);


dbc.executeupdate ("Delete from bylaw _affix where bylawid=" + SID);


Transaction.commit (); Submit JTA Transaction


Dbc.close ();


return 1;


 }


catch (Exception exc) {


try {


Transaction.rollback ();//JTA transaction rollback


  }


catch (Exception ex) {


//JTA Transaction rollback error Handling


Ex.printstacktrace ();


  }


Exc.printstacktrace ();


Dbc.close ();


return-1;


 }


}

















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.