- 可以参考文章
可分为注解以及aop两种形式配置
本例子采用spring+mybatis+springmvc+druid
因为涉及到两个数据库,所以配置了两个 数据源(druid)+ sqlSessionFactory + MapperScannerConfigurer +事务管理器
mybatis.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 读取资源文件替换spring配置文件中的占位符 -->
<context:property-placeholder
ignore-unresolvable="true" location="classpath*:/application.properties" />
<!-- 配置数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="100" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="10000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="testWhileIdle" value="true" />
<!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20" />
<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
<property name="defaultAutoCommit" value="true" />
<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
<property name="validationQuery" value="select 1 " />
<property name="filters" value="stat" />
<property name="proxyFilters">
<list>
<ref bean="logFilter" />
</list>
</property>
</bean>
<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
<property name="statementExecutableSqlLogEnable" value="false" />
</bean>
<!-- 配置业务 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 向属性中注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 自动扫描目录,省掉Configuration.xml里的手工配置Class名与缩写 -->
<property name="typeAliasesPackage" value="com.liandan.bean" />
<!-- 打印sql -->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 没有把mapper文件放到与dao相同的深层目录,显式指定Mapper文件位置 -->
<property name="mapperLocations" value="classpath*:mybatis/*Mapper.xml" />
</bean>
<!-- 扫描mapper目录 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="annotationClass" value="org.springframework.stereotype.Repository"/>
<property name="basePackage" value="com.liandan.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务特性 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="taTransactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="create*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<!--
<tx:method name="Match*" propagation="REQUIRED"/>
-->
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<!--
<tx:method name="testTransactional*" propagation="REQUIRED"/>
-->
</tx:attributes>
</tx:advice>
<!-- AOP配置(切面)-->
<aop:config>
<aop:pointcut id="myPointcut"
expression="execution(public * com.joybo.service.impl.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
</aop:config>
</beans>
//service层代码如下
例子为注解式事务
@Override
@Transactional(value="taTransactionManager",propagation=Propagation.REQUIRED)
public boolean Match(Makemoneyinfo makeMoneyinfo,String remark) throws RuntimeException{
int billtype = makeMoneyinfo.getBilltype();
String customername = makeMoneyinfo.getCustomername();
String makemoneyid = makeMoneyinfo.getId();
String pk_cust = makeMoneyinfo.getPkcustomer();
String accountno = makeMoneyinfo.getAccountnumber();
String money = makeMoneyinfo.getMakemoney();
Map map = new HashMap();
map.put("isMatch",0);map.put("otherpartyNo", accountno);map.put("happenAmount", money);//map.put("pkCust", pk_cust);
List<CwNotice> listCwNotice = cwNoticeMapper.getCwNoticeList(map);
if(listCwNotice.size() == 1){
try{
map.put("isMatch",1);map.put("id", listCwNotice.get(0).getId());map.put("pkCust", pk_cust);
CwNotice cwNotice = listCwNotice.get(0);
//跟新本地
String sarrivaltime = cwNotice.getHappenTime()+cwNotice.getTransTime();
String arrivaltime = DateUtil.getDateTimeFormat(DateUtil.getDateTimeFormatHFS(sarrivaltime));
Map mapmakemoney = new HashMap();mapmakemoney.put("id", makemoneyid);mapmakemoney.put("billstatus",1);mapmakemoney.put("bankid",cwNotice.getBankId());
mapmakemoney.put("vouchertime",DateUtil.getDateTimeFormat(new Date()) );mapmakemoney.put("modifiedtime", DateUtil.getDateTimeFormat(new Date()));
mapmakemoney.put("arrivaltime",arrivaltime);
makemoneyinfoMapper.updateByPrimaryMapKey(mapmakemoney);
//更新中间件
cwNoticeMapper.updateCwNoticeByid(map);
}catch(Exception exception){
//TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
logger.info(remark+"自动匹配失败: 经销商:"+customername+" 打款账户:"+accountno+ " 金额: "+money+" 单据类型:"+(billtype == 1 ? "1:保证金" : "2:违约金") +" 匹配银行流水id: "+listCwNotice.get(0).getBankId());
logger.error(remark+"信息匹配出现异常");
throw new RuntimeException();
}
logger.info(remark+"自动匹配成功: 经销商:"+customername+" 打款账户:"+accountno+ " 金额: "+money+" 单据类型:"+(billtype == 1 ? "1:保证金" : "2:违约金") +" 匹配银行流水id: "+listCwNotice.get(0).getBankId());
return true;
}else{
return false;
}
}
这里的两个数据库不会涉及到分布式事务,所以配置的两个数据源的事务是分离开的,不能被一起管理。
这里考虑同一个数据源的情况
如果想了解分布式事务请参考博主的另一篇文章 Java JDBC事务与JTA分布式事务
cnblogs.com/jasongj/p/5727897.html
1.关于事务的属性配置
主要配置-事务属性:
事务属性通常由事务的传播行为,事务的隔离级别,事务的超时值和事务只读标志组成
传播行为为事务进行嵌套时候(比如service层方法的嵌套),事务的开启关闭策略,需要格外注意的是,因为spring的事务依赖代理实现,如cglib等,所以当同一个service类的事务方法存在嵌套调用时,嵌套在里面的方法的事务是没法开启的。所以可以有两种解决方案:
一。改用代码式事务 :
Spring提供两种方式的编程式事务管理,分别是:使用TransactionTemplate和直接使用PlatformTransactionManager。
采用TransactionTemplate和采用其他Spring模板,如JdbcTempalte和HibernateTemplate是一样的方法。它使用回调方法,把应用程序从处理取得和释放资源中解脱出来。如同其他模板,TransactionTemplate是线程安全的。代码片段:
TransactionTemplate tt = new TransactionTemplate(); // 新建一个TransactionTemplate
Object result = tt.execute(
new TransactionCallback(){
public Object doTransaction(TransactionStatus status){
updateOperation();
return resultOfUpdateOperation();
}
}); // 执行execute方法进行事务管理
使用PlatformTransactionManager
示例代码如下:
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); //定义一个某个框架平台的TransactionManager,如JDBC、Hibernate
dataSourceTransactionManager.setDataSource(this.getJdbcTemplate().getDataSource()); // 设置数据源
DefaultTransactionDefinition transDef = new DefaultTransactionDefinition(); // 定义事务属性
transDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); // 设置传播行为属性
TransactionStatus status = dataSourceTransactionManager.getTransaction(transDef); // 获得事务状态
try {
// 数据库操作
dataSourceTransactionManager.commit(status);// 提交
} catch (Exception e) {
dataSourceTransactionManager.rollback(status);// 回滚
}
二。将两个方法放在不同的类中。
隔离级别:事务并发访问会产生一些问题:比如 脏读 幻读 不可重复读 。可以设置数据库的隔离级别来一定程度减少数据一致性问题。 在spring中可以配置事务管理器的隔离级别属性来控制并发。
事务的超时值和事务只读标志:事务的最大提交时间
事务回滚机制:遇到特定异常回滚或者不回滚
具体使用可参考如下
Spring事务管理与传播机制详解以及使用实例:
https://blog.csdn.net/hcmony/article/details/77850183
https://www.cnblogs.com/yixianyixian/p/8372832.html
.Spring事务的传播:PROPAGATION_REQUIRED
https://blog.csdn.net/happydecai/article/details/80338053
关于事务属性可参考如下:
隔离级别 图标
https://blog.csdn.net/weixin_38070406/article/details/78157603
spring事务隔离级别
https://blog.csdn.net/liaohaojian/article/details/68488150