How to do Rollback with Transactional Annotation

Viewed 178

I am trying to do Transactional Rollback in my methods. Intentionally i am making the insert fails to find out . But i don't see its getting rolled back . Please help what i am missing.

@Service
public class ModesService implements IModesService{

ChargeRuleDao chargeRuleDao;

public ModesService(ChargeRuleDao chargeRuleDao){
    this.chargeRuleDao = chargeRuleDao;
}

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void process(ChargeRule chargeRule){
    chargeRuleDao.deleteShippingChargeAttr(shippingChargeRuleID);
    chargeRuleDao.deleteShippingCharge(shippingChargeRuleID);
    chargeRuleDao.deleteShippingChargeDest(shippingChargeRuleID);

    //Delete
    chargeRuleDao.insertShipChargeFeedRule(chargeRule);
        
}

In DAOImpl class i have methods like below for all deletions and insertion.

@Override
public int deleteShippingChargeAttr(String test) {
    MapSqlParameterSource params = new MapSqlParameterSource();
    params.addValue("ABC" "ABC", Types.VARCHAR);
    return jdbcTemplate.update(DELETE_QUERY, params);

}
2 Answers

You may try @Transactional(rollbackFor = XYZException.class). XYZException should be an exception which should wrap all the exceptions/exception for which you want to rollback the transaction.

Rollback occurs by default for every unchecked exception. That means you need to throw some type unchecked exception, like for example

throw new NullPointerException();

in your insertShipChargeFeedRule(chargeRule);

more about @Transactional here https://javamondays.com/spring-transactions-explained/

Related