I. Preface:
Before writing this blog, we need to understand two concepts: local transaction and distributed transaction.
Local transactions: Only a single data source, such as a single database, is processed.
Distributed transactions: Handling a variety of heterogeneous data sources, such as including JDBC and JMS at the same time in a business operation, or an operation that requires access to multiple different databases.
Java through the JTA to complete the distributed transaction, JTA itself is just a specification, this blog will use JOTM as the implementation, follow-up will also use Atomikos implementation.
two. Business background:
Let's say we have a requirement: when we create a new user, we need to insert a user record into a db, and we need to log in another db.
Because it is a different db operation, it involves the processing of distributed transactions.
three. Code implementation:
1. Code structure diagram:
2. Table statement:
[SQL] view plain copy create database log; DROP TABLE IF EXISTS ' log '; CREATE TABLE ' log ' (' id ' varchar ' NOT NULL, ' content ' varchar () default NULL, PRIMARY KEY (' id ')); Create database user; DROP TABLE IF EXISTS ' user '; CREATE TABLE ' user ' (' id ' varchar ' NOT NULL, ' name ' varchar () default NULL, PRIMARY KEY (' id '));
3. configuration file Applicationcontext.xml
[HTML] View plain copy <?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.springframework.org/schema/tx/spring-tx.xsd http:// www.springframework.org/schema/aop