Java transaction (7)-distributed transaction-spring + JTA + jotm
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
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);}}