---
title: "Spring JTA应用JOTM & Atomikos III Atomikos"
author: "tom.duan"
date: "2007-12-11T16:27:35Z"
tags: ["Hibernate", "Java", "MySQL", "Spring", "应用服务器"]
categories: ["企业架构"]
slug: "spring-jta-jotm-atomikos-iii-atomikos"
draft: false
lastmod: "2007-12-11T16:27:35Z"
id: 147599
url: "https://tom-duan.iteye.com/blog/147599"
---

前面简单介绍了JOTM如何在Spring中配置，并如何使用它的JTA事务，本节将介绍Atomikos如何与Spring集成，并使用它的JTA事务。 Atomikos,是一个基于Java的开源事务管理器，提供了事务管理和连接池，不需要应用服务器支持，支持JDBC和JMS事务，能提供对Spring，Hibernate的集成，有兴趣多了解的可以直接参考说明文当，有详细的介绍和使用说明。 Atomikos可以到http://www.atomikos.com/products.html#ate下载,最新版本是3.2.0 首先,仍然是一个相关的配置文件，用来设置相关的环境,打开解压缩后Atomikos根目录,拷贝jta.properties到classpath中，并修改为如下内容 jta.properties \[code] com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory com.atomikos.icatch.console\_file\_name = tm.out com.atomikos.icatch.log\_base\_name = tmlog com.atomikos.icatch.tm\_unique\_name = com.atomikos.spring.jdbc.tm com.atomikos.icatch.console\_log\_level = INFO \[/code] 随后，是Spring上下文配置，建立一个名为ApplicationContext-atomikos.xml的Spring上下文 ApplicationContext-atomikos.xml \[code] mysql/main com.mysql.jdbc.jdbc2.optional.MysqlXADataSource URL=jdbc:mysql://localhost:3306/test;user=root;password=admin true 3 SELECT 1 mysql/news com.mysql.jdbc.jdbc2.optional.MysqlXADataSource URL=jdbc:mysql://localhost:3306/test2;user=root;password=admin true 3 SELECT 1 true PROPAGATION\_REQUIRED,-Exception \[/code] 看上下文中的代码，很大部分和JOTM的相似，atomikos使用com.atomikos.jdbc.SimpleDataSourceBean类来创建datasource bean，这里需要特别注意 \[code] mysql/main \[/code] \[code] mysql/news \[/code] 上面的代码为每个Datasource配置了一个唯一的名称，名称不允许相同，否则将会使用同一个datasource，而不会出现异常。 另外在配置文件中定义了Atomikos的事务管理器，并在Spring的JtaTransactionManager中引用 \[code] true \[/code] 其它的代码没什么特别，和JOTM配置基本相同，JdbcTemplate，DAO，Service，事务代理等等.... 仍然使用TestXa.java，修改成引用ApplicationContext-atomikos.xml的上下文配置 \[code] protected String\[] getConfigLocations() { //return new String\[] { "classpath:ApplicationContext-jotm.xml" }; return new String\[] { "classpath:ApplicationContext-atomikos.xml" }; } \[/code] 运行test，然后查看数据库状态， 然后修改方法参数使其不违反数据库约束，再运行Test观察数据库 ：）。