在项目中有很多地方会使用到独立事务,下面以获取主键为例
(1)修改配置文件spring-mybatis.xml
<!-- 开启事务支持 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 拦截器方式配置事务 -->
<!-- 定义service事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义方法的过滤规则 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="merge*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="put*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="count*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="list*" propagation="SUPPORTS" read-only="true" />
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
<!-- 获取主键开启独立事务 -->
<tx:method name="getPKId" propagation="REQUIRES_NEW" />
</tx:attributes>
</tx:advice>
<!--AOP配置 -->
<aop:config proxy-target-class="true">
<!-- 适配切入点 和 事务的通知 -->
<aop:pointcut id="txPointcut"
expression="execution(* *..*SVImpl.*(..))" />
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice" />
</aop:config>
(2)服务层新增接口和方法
新增接口
ICommonSV
新增方法
public long getPKId(String tableName) throws Exception;
新增实现类
CommonSVImpl
新增方法
public long getPKId(String tableName) {
long seq = -1;
StringBuilder sb = new StringBuilder();
sb.append(" SELECT ");
sb.append(tableName).append("$SEQ.NEXTVAL SEQ ");
sb.append(" FROM DUAL ");
Map map = new HashMap();
try {
map = executeQuerySql(sb.toString()).get(0);
} catch (Exception e) {
throw new ZCrmException("["+tableName+"]获取主键失败:"+e.getMessage());
}
seq = Long.parseLong(map.get("SEQ").toString());
log.info(tableName+"$SEQ:"+seq);
return seq;
}
@Autowired
private ICommonDAO ICommonDAO;
private synchronized List<Map> executeQuerySql(String sql) throws Exception {
List<Map> o = null;
o = ICommonDAO.executeQuerySql(new SQLAdapter(sql));
return o;
}