为什么事务管理在Spring中失败,具有以下配置。即使抛出RuntimeException,事务也不会回滚。好吧,我是为了学习目的手动抛出它。
我的Dao课程:
@Transactional(rollbackFor=ArithmeticException.class)
public class TransactionAnnotationDaoImpl extends JdbcDaoSupport implements JdbcDao {
public void create(Student student) {
try {
String sql = "insert into student values (?,?,?)";
getJdbcTemplate().update(sql,student.getAge(), student.getName(), student.getId());
String marksSql="insert into marks values (?,?,?)";
int i=2/0; //added to depict roll back behaviour of the transaction when exception occurs
getJdbcTemplate().update(marksSql,student.getId(),student.getSubject(),student.getMarks());
System.out.println("transaction committed");
} catch (RuntimeException e) {
e.printStackTrace();
System.out.println("transaction rolled back");
}
}
}
我的弹簧配置文件内容:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"></property>
<property name="url" value="jdbc:derby://localhost:1527/db;create=true"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="annotationTransactionDaoImpl" class="org.sujay.springjdbc.dao.TransactionAnnotationDaoImpl">
<property name="dataSource" ref="dataSource"></property></bean>
我正在通过以下调用从main方法调用dao:
JdbcDao annotationDao = context.getBean("annotationTransactionDaoImpl", JdbcDao.class);
annotationDao.create(new Student(25, "p", 4, 19, "cn2"));
但交易没有回滚。学生表中有一个条目,但标记表没有,这意味着交易失败。请帮我解决这个问题。
答案 0 :(得分:0)
因为你抓住了例外。
删除try catch或重新抛出异常:
try{
...
} catch (RuntimeException e) {
e.printStackTrace();
System.out.println("transaction rolled back");
throw e; //rethrow so spring will recognize it
}