配置跨数据库的事务控制
2016-04-22 10:07
337 查看
1 导入包
2 配置XML文件
<?xml
version="1.0"encoding="UTF-8"?>
<web-app
version="3.0"xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name>
<!-- log4jConfigLocation:log4j配置文件存放路径 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
内容如下:
# Configure logging for testing:optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d
%p [%c]
- %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d
%p [%c]
- %m%n
3写类方法
package com.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.XAConnection;
import javax.transaction.UserTransaction;
import org.enhydra.jdbc.standard.StandardXADataSource;
import org.objectweb.jotm.Jotm;
import org.objectweb.transaction.jta.TMService;
/**
* 分布式业务处理类
*
* @authorAdministrator
*
*/
public class JotmHelper {
public finalString YHConn = "YHConn";// 连接YH
public finalString LocalConn = "LocalConn";// 连接本地
private staticString url = "";
private staticString user = "";
private staticString pwd = "";
privateTMService jotm;
privateUserTransaction userTransaction;
privateXAConnection xaconn = null;
//InitialContext ctx = null;// new InitialContext();
//
publicJotmHelper() {
}
/**
* @param connName数据库名称
* @return
* @throws Exception
*/
publicConnection getConnection(String connName) throws Exception {
StandardXADataSourcexads = new StandardXADataSource();
// ctx = newInitialContext();
// 本地
if(connName.equals("LocalConn")) {
// 获取配置文件类
DBasePropertiesdProperties = new DBaseProperties();
url =dProperties.GetPropertiesUrl().trim();// 获取URL
user =dProperties.GetPropertiesUser().trim();// 获取数据库登录名称
pwd =dProperties.GetPropertiesPwd().trim();// 获取数据库登录密码
// SQL2005
xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//
// 驱动查询
xads.setUrl(url);
xads.setTransactionManager(jotm.getTransactionManager());
xaconn =xads.getXAConnection(user, pwd);
}
// YH物流
else if(connName.equals("YHConn")) {
// 获取配置文件类
YHDBasePropertiesyHProperties = new YHDBaseProperties();
url =yHProperties.GetPropertiesUrl().trim();// 获取URL
user =yHProperties.GetPropertiesUser().trim();// 获取数据库登录名称
pwd =yHProperties.GetPropertiesPwd().trim();// 获取数据库登录密码
// SQL2005
xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//
// 驱动查询
xads.setUrl(url);
xads.setTransactionManager(jotm.getTransactionManager());
xaconn =xads.getXAConnection(user, pwd);
// intlevel=0;
// xaconn.getConnection().setTransactionIsolation(level);
}
returnxaconn.getConnection();
}
/**
* 启动事务管理服务
*/
public voidstartTMService() {
try {
// 实例化事务管理器
jotm =new Jotm(true, false);
userTransaction= jotm.getUserTransaction();
} catch(NamingException e1) {
e1.printStackTrace();
}
}
/**
* 停止事务管理服务
*/
public voidstopTMService() {
jotm.stop();
jotm = null;
}
/**
* 事务开始
*/
public voidbegin() {
try {
userTransaction.begin();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 事务提交
*/
public voidcommit() {
try {
userTransaction.commit();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 事务回滚
*/
public voidrollback() {
try {
userTransaction.rollback();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 关闭数据库连接
*/
public voidcloseConn() {
try {
if(xaconn != null) {
xaconn.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
调用
public boolean addPurchase(En_Purchase enPurchase) {
//
long start =System.currentTimeMillis();
jotmHelper = newJotmHelper();
enPurchaseDao= new En_PurchaseDao();
enPurchaseDetaileDao= new En_PurchaseDetaileDao();
boolean flag= false;
booleanoperbool = false;
introwsCount = 0;
try {
jotmHelper.startTMService();//开启事务
Connectionconn = jotmHelper.getConnection("LocalConn");//
本地
//开始事务
jotmHelper.begin();
// 获取是否存在相同记录
rowsCount= enPurchaseDao.getPurchaseCountById(enPurchase.getPur_Id().trim(), conn);
if(rowsCount == 0) {
// 添加Dispatch主表
operbool= enPurchaseDao.addPurchase(enPurchase, conn);// 添加
} elseif ((rowsCount > 0)) {
operbool= enPurchaseDao.updateEnPurchase(enPurchase, conn);// 修改
}
// 如果主表插入成功
if(operbool == true) {
if(enPurchase.getEnPurchaseDetaileList() != null &enPurchase.getEnPurchaseDetaileList().size() > 0) {
//给集合链表赋值
List<En_PurchaseDetaile>tempList = enPurchase.getEnPurchaseDetaileList();
//添加Dispatch明细
flag= enPurchaseDetaileDao.addPurchaseDetaile(tempList, conn);//
jotmHelper.commit();//提交
flag= true;
longend = System.currentTimeMillis();
System.out.println("addPurchase:\t"+ "commit...");
System.out.println("运行时间:"+ (end - start) + "毫秒");
}
}
} catch(Exception e) {
flag =false;
jotmHelper.rollback();
} finally {
jotmHelper.stopTMService();//
jotmHelper.closeConn();
}
return flag;
}
2 配置XML文件
<?xml
version="1.0"encoding="UTF-8"?>
<web-app
version="3.0"xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name>
<!-- log4jConfigLocation:log4j配置文件存放路径 -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
内容如下:
# Configure logging for testing:optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d
%p [%c]
- %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d
%p [%c]
- %m%n
3写类方法
package com.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.sql.XAConnection;
import javax.transaction.UserTransaction;
import org.enhydra.jdbc.standard.StandardXADataSource;
import org.objectweb.jotm.Jotm;
import org.objectweb.transaction.jta.TMService;
/**
* 分布式业务处理类
*
* @authorAdministrator
*
*/
public class JotmHelper {
public finalString YHConn = "YHConn";// 连接YH
public finalString LocalConn = "LocalConn";// 连接本地
private staticString url = "";
private staticString user = "";
private staticString pwd = "";
privateTMService jotm;
privateUserTransaction userTransaction;
privateXAConnection xaconn = null;
//InitialContext ctx = null;// new InitialContext();
//
publicJotmHelper() {
}
/**
* @param connName数据库名称
* @return
* @throws Exception
*/
publicConnection getConnection(String connName) throws Exception {
StandardXADataSourcexads = new StandardXADataSource();
// ctx = newInitialContext();
// 本地
if(connName.equals("LocalConn")) {
// 获取配置文件类
DBasePropertiesdProperties = new DBaseProperties();
url =dProperties.GetPropertiesUrl().trim();// 获取URL
user =dProperties.GetPropertiesUser().trim();// 获取数据库登录名称
pwd =dProperties.GetPropertiesPwd().trim();// 获取数据库登录密码
// SQL2005
xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//
// 驱动查询
xads.setUrl(url);
xads.setTransactionManager(jotm.getTransactionManager());
xaconn =xads.getXAConnection(user, pwd);
}
// YH物流
else if(connName.equals("YHConn")) {
// 获取配置文件类
YHDBasePropertiesyHProperties = new YHDBaseProperties();
url =yHProperties.GetPropertiesUrl().trim();// 获取URL
user =yHProperties.GetPropertiesUser().trim();// 获取数据库登录名称
pwd =yHProperties.GetPropertiesPwd().trim();// 获取数据库登录密码
// SQL2005
xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//
// 驱动查询
xads.setUrl(url);
xads.setTransactionManager(jotm.getTransactionManager());
xaconn =xads.getXAConnection(user, pwd);
// intlevel=0;
// xaconn.getConnection().setTransactionIsolation(level);
}
returnxaconn.getConnection();
}
/**
* 启动事务管理服务
*/
public voidstartTMService() {
try {
// 实例化事务管理器
jotm =new Jotm(true, false);
userTransaction= jotm.getUserTransaction();
} catch(NamingException e1) {
e1.printStackTrace();
}
}
/**
* 停止事务管理服务
*/
public voidstopTMService() {
jotm.stop();
jotm = null;
}
/**
* 事务开始
*/
public voidbegin() {
try {
userTransaction.begin();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 事务提交
*/
public voidcommit() {
try {
userTransaction.commit();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 事务回滚
*/
public voidrollback() {
try {
userTransaction.rollback();
} catch(Exception e) {
e.printStackTrace();
}
}
/**
* 关闭数据库连接
*/
public voidcloseConn() {
try {
if(xaconn != null) {
xaconn.close();
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
调用
public boolean addPurchase(En_Purchase enPurchase) {
//
long start =System.currentTimeMillis();
jotmHelper = newJotmHelper();
enPurchaseDao= new En_PurchaseDao();
enPurchaseDetaileDao= new En_PurchaseDetaileDao();
boolean flag= false;
booleanoperbool = false;
introwsCount = 0;
try {
jotmHelper.startTMService();//开启事务
Connectionconn = jotmHelper.getConnection("LocalConn");//
本地
//开始事务
jotmHelper.begin();
// 获取是否存在相同记录
rowsCount= enPurchaseDao.getPurchaseCountById(enPurchase.getPur_Id().trim(), conn);
if(rowsCount == 0) {
// 添加Dispatch主表
operbool= enPurchaseDao.addPurchase(enPurchase, conn);// 添加
} elseif ((rowsCount > 0)) {
operbool= enPurchaseDao.updateEnPurchase(enPurchase, conn);// 修改
}
// 如果主表插入成功
if(operbool == true) {
if(enPurchase.getEnPurchaseDetaileList() != null &enPurchase.getEnPurchaseDetaileList().size() > 0) {
//给集合链表赋值
List<En_PurchaseDetaile>tempList = enPurchase.getEnPurchaseDetaileList();
//添加Dispatch明细
flag= enPurchaseDetaileDao.addPurchaseDetaile(tempList, conn);//
jotmHelper.commit();//提交
flag= true;
longend = System.currentTimeMillis();
System.out.println("addPurchase:\t"+ "commit...");
System.out.println("运行时间:"+ (end - start) + "毫秒");
}
}
} catch(Exception e) {
flag =false;
jotmHelper.rollback();
} finally {
jotmHelper.stopTMService();//
jotmHelper.closeConn();
}
return flag;
}
相关文章推荐
- 监控 Redis 服务方案
- java对redis的基本操作
- 解决 Maven oracle驱动无法下载到的问题
- Oracle中注释多行有快捷键吗,是什么?
- H2数据库的有点以及如何使用
- MySql数据基本操作sql语句
- sqlalchemy
- 用distinct在MySQL中查询多条不重复记录值
- TimesTen 应用层数据库缓存学习:11. AWT性能监控
- Oracle flashback table简介
- Mybatis like 查询 防止SQL注入方法相关原理和解决方法整理
- mysql视图学习总结
- mysql教程导出数据库教程几种方法
- mysql 5.7 版本,密码无法登陆,更改密码时出现ERROR 1054 (42S22): Unknown column 'password' in 'fie
- 附加数据库失败,sql2008,断电数据库日志受损
- ORACLE创建表空间和用户
- MySQL安装过程net start mysql 启动失败 报“错误2,系统找不到文件”的解决办法
- 青云 ubuntu下mysql远程连接配置
- plsql developer创建连接DBlinks
- ssh连接Linux导出oracle数据