首页 文章

Spring :: @Transactional无效

提问于
浏览
0

我是Spring的新手并且学习了交易概念 . 无法让@Transactional工作 .

Use Case:
当getEmployee()抛出RunTimeException时,Employee和Employee详细信息的数据插入应该回滚 . 但回滚没有发生 . 我正在使用Oracle数据库11g和spring 4.3.1.RELEASE . 下面是我正在运行的独立java代码 .

代码

public static void main(String [] args){AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(“spring-bean.xml”); ctx.registerShutdownHook();

Employee emp = new Employee("149518", "Mickey", "Mouse", "15 years", "tennis");

IEmployee empIntfc = (IEmployee)ctx.getBean("empService");
try {
        empIntfc.createEmployee(emp);
        empIntfc.createEmployeeDetails(emp);

        //Below will throw RunTime Exception
        empIntfc.getEmployee(2);

    }catch (Exception e ) {
        e.printStackTrace();

    } finally {
        ctx.close();    
    }

}

EmployeeService.java

public class EmployeeService implements IEmployee {

private DataSource dataSource;
private JdbcTemplate jdbcTemplate;

public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}

@Override
@Transactional
public int createEmployee(Employee emp) {       

    String sql1 = "INSERT INTO TEST_T1(EMP_ID, EMP_FNAME, EMP_LNAME) values   
    (?,?,?)";
    return getJdbcTemplate().update(sql1, emp.getEmpId(), 
    emp.getEmpFirstName(), emp.getEmpLastName());
}

@Override
@Transactional
public int createEmployeeDetails(Employee emp) {

    String sql = "INSERT INTO TEST_T2(EMP_ID, EXP, SKILLS) values (?,?,?)";     
    return getJdbcTemplate().update(sql, emp.getEmpId(), emp.getExp(), 
    emp.getSkills());
}

@Override
@Transactional(readOnly = true, noRollbackFor=RuntimeException.class)
public Employee getEmployee(int empId) {
    throw new RuntimeException("Intentional runtime exception");
}

}

spring-bean.xml

<beans xmlns="http://www.springframework.org/schema/beans">

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

<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource"   
  class="org.springframework.jdbc.datasource.DriverManagerDataSource"  >
  <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
  <property name="url" value="jdbc:oracle:thin:@//xxxx:1521/xxxx"/>
  <property name="username" value="user"/>
  <property name="password" value="user"/>
  </bean> 
  <bean id="empService" class="com.service.EmployeeService">
  <property name="dataSource" ref="dataSource"/>
  </bean>   
  </beans>

1 回答

  • 1

    您的主要方法不是事务性的...意味着:输入'createEmployee'创建一个新事务并提交它,'createEmployeeDetails'创建一个新事务并提交它 .

相关问题