Search code examples
javaspring-mvctransactional

@Transactional not rolling back


I have literally wasted the whole day trying to figure out why my DML statement is not getting rolled back. Although I have done a thorough search on the internet and as well as on stackoverflow - I am not able to wrap my head around it.

I am not trying to catch the below exception any where via try catch or @ExceptionHandler or @ControllerAdvice. Not able to figure out why my query is not getting rolled back. This question sounds like a duplicate but none of the other posts on stackoverflow could solve my problem

spring.xml

<bean id="employeeImpl" class="org.daoImpl.EmployeeImpl">
    <property name="dataSource" ref="dataSource"></property>
</bean>

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

Controller

@RequestMapping(value = "/formSubmit", method = RequestMethod.POST)
public ModelAndView handleForm(@ModelAttribute("employee") Employee employee) {

    ModelAndView modelAndView = new ModelAndView("Success");
    employeeImpl.insertEmployee(employee);
    return modelAndView;
}

And finally the method that needs to be rolled back

@Transactional(rollbackFor=RuntimeException.class)
public void insertEmployee(Employee emp) {
    String SQL = "insert into employee values(?,?,?,?,?)";
    getJdbcTemplate().update(SQL, new Object[] { emp.getId(),emp.getFname());
    throw new RuntimeException("I am throwing you out!");
}

I am using MySQL as my database.

Even after the runtime exception is thrown the insert query persists in the database, it should be rolled back right? Can someone please tell me what I am missing


Solution

  • The transaction was not getting rolled back as the table's engine was MyISAM. This particular engine DOES NOT support transactions as rightly pointed out by TJ ( which I did not know!)

    I have changed my table's engine to InnoDB and the transaction is getting rolled back as expected.

    Thank you again TJ!