edio
edio

Reputation: 662

Test jdbcTemplate.batchUpdate with rollback by default

I'm trying to test my dao, that uses jdbcTemplate.batchUpdate method under the hood.

My tests are run against real datasource and all methods are performed in transactions marked as rollback-only (any changes are rolled back after the test). Test transactions are managed by PlatformTransactionManager.

The issue here, is that jdbcTemplate.batchUpdate seems to be executed in separate transaction started by DataSourceTransactionManager and thus, I can't see changes made by jdbcTemplate.

My test:

@Transactional
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true)
@RunWith(SpringJUnit4ClassRunner.class)
public abstract class AbstractDbUnitTest
...
@Test
public void removeSpecific() {
    myDao.removeSpecific(myDao.findAllAliasedItems());
    Assert.assertEquals(0, myDao.findAllAliasedItems().size());
}

Dao

@Override
public void removeSpecific(final List<? extends Item> items) {
    jdbcTemplate.batchUpdate("delete from ITEM where item_type = ? and item_id = ?", new BatchPreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, items.get(i).getType().name());
            ps.setString(2, items.get(i).getId(););
        }

        @Override
        public int getBatchSize() {
            return items.size();
        }
    });
}

Is there any way to test batchUpdate method item without actually altering the data? Thanks in advance.

Upvotes: 1

Views: 2181

Answers (1)

edio
edio

Reputation: 662

I'm sorry for misleading you all. The issue was not caused by nested transaction. This question is a result of my total misunderstanding of the hierarchy of transactions-related classes in Java and how batch statements in JDBC implemented.

Test was failing because subsequent calls to

myDao.findAllAliasedItems()

were cached. Spring JDBC template worked just fine and as one might expect.

Upvotes: 0

Related Questions