mybatis+spring 如何进行手动事务控制

jestymat 2015-03-09 01:29:00
先贴一下代码
applicationContext.xml

<?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" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config></context:annotation-config>
<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
<property name="url" value="jdbc:db2://ip/dbname"/>
<property name="username" value="username" />
<property name="password" value="pwd" />
</bean>


<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="jfAccountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.xxx.interfaces.JfAccountMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans


*.java 某个用到事务的action

public class *Action extends ActionSupport{
private JfAccountMapper jfAccountMapper ;
public void setJfAccountMapper(JfAccountMapper jfAccountMapper ){
this.jfAccountMapper = jfAccountMapper ;
}
public JfAccountMapper getJfAccountMapper (){
return jfAccountMapper ;
}

@Tansactional
public String save(){
JfAccount obj = new JfAccount();
obj.setProperty(); //
jfAccountMapper .insert();

flag = true; // 这里设置一个标志用于ajax提交返回结果
return SUCCESS
}
}




设置action的时候这个save()方法是作为 json返回,使用ajax提交后,需要一个返回值。
现在是,save()时发生错误,事务能够回滚,但是ajax无法接收到返回信息。
如果把 save()放到一个try catch中,无法catch到任何异常(好像是@transcational自动处理了异常),
如果把 save中的涉及数据库操作的代码放到try catch中,自己能捕捉到异常,但是事务又不会回滚
...全文
15594 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
豫让_______ 2015-03-09
  • 打赏
  • 举报
回复
http://blog.csdn.net/andyxuq/article/details/7982143 看看这个吧,try catch里面加一个操作就可以了。
jestymat 2015-03-09
  • 打赏
  • 举报
回复
终于找到了解决方法, 具体见 https://mybatis.github.io/spring/zh/transactions.html

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧