Spring:Propagation.REQUIRED not working

戏子无情 提交于 2019-12-04 19:20:25

The problem is your catch block. Since the exception is catched the tx don't rollback.

You must throw the exception :

public void saveEmployee(Employee empl){
    try {
        jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
                empl.getDeptId(),empl.getAge(),empl.getSex());
    } catch (DataAccessException e) {
        e.printStackTrace();
        throw e;
    }

}

And by the way, the semantic of Progation.Required just means : create a new tx if it don't exists OR use an existing one if there is tx running.


Following your comment here is a suggestion to see the effect of NEW tx :

@Transactional(propagation=Propagation.REQUIRES_NEW)
public void saveEmployee(Employee empl){
    try {
        jdbcTemplate.update("INSERT INTO EMP VALUES(?,?,?,?,?)",empl.getEmpId(),empl.getEmpName(),
                empl.getDeptId(),empl.getAge(),empl.getSex());
    } catch (DataAccessException e) {
        e.printStackTrace();
        throw e;
    }

}

@Transactional(propagation=Propagation.REQUIRED)
public void saveRecords(){
    saveDepartment(dept);
    try{
       saveEmployee(empl);
    }catch(Exception e){Logger.log("Fail to save emp !");}     
}

The key point to see the effect of REQUIRES_NEW is to catch the exception around saveEmployee. If you don't catch it : the exception will propagate in the other tx (the one started when entering saveRecords() ) and it will rollback too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!