wormwood87
wormwood87

Reputation: 153

jdbcTemplate.batchUpdate rollback is not working

I have a SpringBoot application. I have Services to call REST operations. In my Put I'm calling my repository where I'm doing a jdbcTemplate.batchUpdate(where he updated table A and inserts data on table B). The size of the list is about 30000 so I'm using a batchSize of 100. To test that the rollback works, in my code I'm throwing an exception on purpose after it completes the first batch of 100, it leaves on error but the rollback is not working.

Service:

@Transactional(rollbackFor = Exception.class)
@Override
public void put(String name1, String name2) {
    try {
        repo.doStuff(name1, name2);
    }
    catch (Exception e) {
        //do stuff
    }
}

Repo:

@Override
public void doStuff(String name1, String name2) {
    // ...
    List<Book> list = getBooks(name1, name2);
    
    for (int i = 0; i < list.size(); i += 100) {
        List<Book> batchList = list.subList(i, Math.min(i + 100, list.size()));
        jdbcTemplate.execute(SET_SCHEMA);
        int error = i;
        int[][] batchUpdateCounts = jdbcTemplate.batchUpdate(SQL_QUERY, batchList, 100, new ParameterizedPreparedStatementSetter<Book>() {
            public void setValues(PreparedStatement ps, Book b) throws SQLException {
                ps.setShort(1, r.getName()));
                if(error == 100) { // to create an exception
                    throw new SQLException("error");
                }
            }
        });
    
        for (int j = 0; j < batchUpdateCounts.length; j++) {
            if (batchUpdateCounts[i][j] == 0) {
                System.out.println("Batch update failed: row " + (i + j) + " was not updated");
            }
        }
    }
        
}

Logs:

2024-07-15T11:48:00.682+02:00 DEBUG 38485 --- [@executable.nom@] [           main] o.s.jdbc.support.JdbcTransactionManager  : Initiating transaction rollback
2024-07-15T11:48:00.682+02:00 DEBUG 38485 --- [@executable.nom@] [           main] o.s.jdbc.support.JdbcTransactionManager  : Rolling back JDBC transaction on Connection [425149044, URL=xxxx, PostgreSQL JDBC Driver]
2024-07-15T11:48:00.683+02:00 DEBUG 38485 --- [@executable.nom@] [           main] o.s.jdbc.support.JdbcTransactionManager  : Releasing JDBC Connection [425149044, URL=xxxx, PostgreSQL JDBC Driver] after transaction

Upvotes: 0

Views: 36

Answers (0)

Related Questions