user3656511
user3656511

Reputation: 53

Why JdbcTemplate.batchupdate(sql[]) method not roll back in Spring4 using @transaction annotation?

The below code is not working for rollback when any exception occurs while insertion of records in database.I am using Spring 4 framework and annotation .

*/I am using below code for transaction management and it will not roll back for any exception./

@Transactional(rollbackFor = RuntimeException.class)
public boolean insertBatch(List<String> query) throws SQLException   {
    boolean flag= false;
    try
    {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

        String[] Sql= query.toArray(new String[query.size()]);
        jdbcTemplate.batchUpdate(Sql);

        flag=true;

    }catch(DataAccessException e )
    {
        flag=false;
        MessageResource.setMessages("Constraints Violation ! CSV data value not matched with database constraints  ");
        LOGGER.info("CSV file Data not  expected as  database table structure defination like constraint violation/Data Type lenght/NUll etc for same data value" );
        LOGGER.error( "Cause for error:  "+  e.getRootCause().getMessage());
        LOGGER.debug( "Details explain : "+  e.toString());
        throw new RuntimeException("Roll back operation");
        //transactionManager.rollback(status);

    }
         return flag;


}**

Upvotes: 2

Views: 11509

Answers (3)

user3656511
user3656511

Reputation: 53

Actually the answer provided by Sir, M.Deinum is below:

Spring uses proxies to apply AOP this will only work for methods called from the outside. Internal method calls don't pass through the proxy hence no transactions and depending on your queries you get one large or multiple smaller commits. Make sure that the outer method (the one called to initiate everything) is transactional. – M. Deinum 14 hours ago

Upvotes: 2

Curious Coder
Curious Coder

Reputation: 69

Use Prepared statement from connection object and the do a execute batch object. On the connection object use conn.setAutoCommit(false). Prepeared statement has 4 times better performance than JdbcTemplate for batch insertion of 1000 records.

Reference : JdbcTemplate.batchUpdate() returns 0, on insert error for one item but inserts the remaining item into sql server db despite using @Transactional

Upvotes: 0

gpeche
gpeche

Reputation: 22514

@Transactional(rollbackFor = RuntimeException.class)

This will rollback only if a RuntimeException or a subclass is thrown from the annotated method. If you want to rollback for any Exception (such as SQLException, which is NOT a RuntimeException), you should do:

@Transactional(rollbackFor = Exception.class)

And if you want to try a rollback for whatever error that might happen

@Transactional(rollbackFor = Throwable.class)

Altough in this last case the runtime might be so broken that not even the rollback can complete.

Upvotes: 0

Related Questions