Java transactions (7): java transactions
I. Preface:
Before writing this blog, we need to understand two concepts: local transactions and distributed transactions.
Local transactions: only process a single data source, such as a single database.
Distributed transactions: process multiple heterogeneous data sources. For example, a service operation contains JDBC and JMS, or an operation needs to access multiple different databases.
Java completes distributed transactions through JTA. JTA itself is only a specification. This blog will use JOTM for implementation and will use Atomikos for implementation in the future.
Ii. business background:
Assume that we have the following requirement: When we create a user, we need to insert a user record into a database and record the log in another database.
Because it is a different DB operation, distributed transaction processing is involved here.
Iii. Code implementation:
1. code structure:
2. Table creation statement:
create database log;DROP TABLE IF EXISTS `log`;CREATE TABLE `log` ( `id` varchar(20) NOT NULL, `content` varchar(100) default NULL, PRIMARY KEY (`id`));create database user;DROP TABLE IF EXISTS `user`;CREATE TABLE `user` ( `id` varchar(20) NOT NULL, `name` varchar(40) default NULL, PRIMARY KEY (`id`));
3. configuration file ApplicationContext. xml
<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.sprin Gframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <! -- Reference factory classes supported by Spring for JOTM --> <bean id = "jotm" class = "org. springframework. transaction. jta. JotmFactoryBean"/> <! -- Configure the JTA Transaction Manager and use the JOTM --> <bean id = "txManager" class = "org. springframework. transaction. jta. jtaTransactionManager "> <property name =" userTransaction "ref =" jotm "/> </bean> <! -- Configure multiple data sources --> <bean id = "db1" class = "org. enhydra. jdbc. pool. standardXAPoolDataSource "destroy-method =" shutdown "> <property name =" dataSource "> <bean class =" org. enhydra. jdbc. standard. standardXADataSource "destroy-method =" shutdown "> <property name =" transactionManager "ref =" jotm "/> <property name =" driverName "value =" com. mysql. jdbc. driver "/> <property name =" url "value =" jdbc: MySQL: // localhost: 3306/user "/> </B Ean> </property> <property name = "user" value = "root"/> <property name = "password" value = "root"/> </bean> <bean id = "db2" class = "org. enhydra. jdbc. pool. standardXAPoolDataSource "destroy-method =" shutdown "> <property name =" dataSource "> <bean class =" org. enhydra. jdbc. standard. standardXADataSource "destroy-method =" shutdown "> <property name =" transactionManager "ref =" jotm "/> <property name =" driverName "value =" com. m Ysql. jdbc. driver "/> <property name =" url "value =" jdbc: MySQL: // localhost: 3306/log "/> </bean> </property> <property name =" user "value =" root "/> <property name =" password "value =" root" /> </bean> <! -- Configure two jdbctemplates based on different data sources --> <bean id = "jdbcTemplate1" class = "org. springframework. jdbc. core. jdbcTemplate "> <property name =" dataSource "ref =" db1 "/> </bean> <bean id =" jdbcTemplate2 "class =" org. springframework. jdbc. core. jdbcTemplate "> <property name =" dataSource "ref =" db2 "/> </bean> <bean id =" userDao "class =" com. zdp. dao. userDao "> <property name =" jdbcTemplate "ref =" jdbcTemplate1 "/> </bean> <bean id =" logDao" Class = "com. zdp. dao. logDao "> <property name =" jdbcTemplate "ref =" jdbcTemplate2 "/> </bean> <bean id =" userService "class =" com. zdp. service. userService "> <property name =" userDao "ref =" userDao "/> <property name =" logDao "ref =" logDao "/> </bean> <! -- JTA transaction propagation feature --> <tx: advice id = "txAdviceJTA" transaction-manager = "txManager"> <tx: attributes> <tx: method name = "save *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "add *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "create *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "insert *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "del *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "update *" isolation = "DEFAULT" propagation = "REQUIRED" rollback-for = "Exception"/> <tx: method name = "*" read-only = "true"/> </tx: attributes> </tx: advice> <aop: config> <aop: advisor pointcut = "execution (* com. zdp. service .. *(..)) "advice-ref =" txAdviceJTA "/> </aop: config> </beans>
4. service class:
Public class UserService {private UserDao userDao; private LogDao logDao; public void saveUser (String id, String name) {userDao. insertUser (id, name); // int I = 1/0; // create a logDao exception. insertLog (id, id + "_" + name);} public UserDao getUserDao () {return userDao;} public void setUserDao (UserDao userDao) {this. userDao = userDao;} public LogDao getLogDao () {return logDao;} public void setLogDao (LogDao logDao) {this. logDao = logDao ;}}
5. Dao class:
public class UserDao extends JdbcDaoSupport {public void insertUser(String id, String name) {JdbcTemplate template = getJdbcTemplate();template.execute("insert into user values('" + id + "','" + name + "')");}}
public class LogDao extends JdbcDaoSupport {public void insertLog(String id, String content) {JdbcTemplate template = getJdbcTemplate();template.execute("insert into log values('" + id + "','" + content + "')");}}
6. Test class:
public class UserTest {@Testpublic void testSave() {ApplicationContext cxt = new ClassPathXmlApplicationContext("ApplicationContext.xml");UserService us = (UserService) cxt.getBean("userService");us.saveUser("1", "zhangsan");}}
Source code download: http://download.csdn.net/detail/zdp072/7950383
Java transactions
Java Transaction Processing
Generally, the J2EE Application Server supports JDBC transactions, JTA (Java Transaction API) transactions, and container management transactions. Generally, it is better not to use the above three transaction types in the program at the same time, such as nesting JDBC transactions in JTA transactions. Second, the transaction should be completed in the shortest time. Do not use the transaction in different methods. The following lists two transaction processing methods.
1. Use JDBC for transaction processing in JavaBean
In JDBC, how does one combine multiple SQL statements into one transaction? In JDBC, when a Connection object is opened, the default mode is auto-commit. Each SQL statement is treated as a transaction, that is, each statement is automatically confirmed by the transaction. In order to combine multiple SQL statements into a transaction, We need to block the auto-commit mode. If the commit () method is not called after the auto-commit mode is disabled, the SQL statement will not be confirmed by the transaction. All SQL statements after the last call of the commit () method are confirmed when the method commit () is called.
Public int delete (int sID ){
Dbc = new DataBaseConnection ();
Connection con = dbc. getConnection ();
Try {
Con. setAutoCommit (false); // change the default commit method of JDBC transactions
Dbc.exe cuteUpdate ("delete from bylaw where ID =" + sID );
Dbc.exe cuteUpdate ("delete from bylaw _ content where ID =" + sID );
Dbc.exe cuteUpdate ("delete from bylaw _ affix where bylawid =" + sID );
Con. commit (); // submit a JDBC transaction
Con. setAutoCommit (true); // restore the default commit Method for JDBC transactions
Dbc. close ();
Return 1;
}
Catch (Exception exc ){
Con. rollBack (); // roll back JDBC transactions
Exc. printStackTrace ();
Dbc. close ();
Return-1;
}
}
2. JTA transactions in SessionBean
JTA is a J2EE solution for transaction services. Essentially, it is part of the J2EE model that describes the transaction interface (such as the UserTransaction interface, which developers directly use or use through the J2EE container to ensure that the business logic can run reliably. JTA has three main interfaces: UserTransaction interface, TransactionManager interface, and Transaction interface. These interfaces share common transaction operations, such as commit () and rollback (), but also include special transaction operations, such as suspend (), resume (), and enlist (), they only appear on specific interfaces to allow a certain degree of access control in the implementation. For example, UserTransaction can perform Transaction Division and basic transaction operations, while TransactionManager can perform context management.
The application can call the UserTransaction. begin () side ...... the remaining full text>
In java transactions
Here is a detailed description of mianshi.fenzhi.com/post/522.html !!