Search code examples
javaspring-bootjdbcjdbctemplatespring-transactions

Can JdbcTemplate Share a Common Transaction?


So I originally posted a question here regarding an issue I was having with mixing JDBC Templates/JPA.

However I'm wondering now if it's even possible to share a common transaction between JDBC Template operations?

Example will update table 'test' in separate transactions.

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void storeDataInSingleTransaction(List<Test> testEntries) {
        namedParameterJdbcTemplate.update("DELETE FROM test", new HashMap<>());
        namedParameterJdbcTemplate.update("alter table test auto_increment = 1", new HashMap<>());

        String insertTestSQL = "INSERT INTO test VALUES (:id, :name, :value)";
        SqlParameterSource[] testBatch = SqlParameterSourceUtils.createBatch(testEntries.toArray());
        namedParameterJdbcTemplate.batchUpdate(insertTestSQL, testBatch);
    }

EDIT 1: I have tried creating the template/data source manually, with Transactional annotation, but has not been successful for me.

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();

    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername(user);
    dataSource.setPassword(password);

    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);


Solution

  • Normally in Spring, when you call your method from @Transactional method it should execute as a single connection

    It is not sufficient to tell you simply to annotate your classes with the @Transactional annotation, add @EnableTransactionManagement to your configuration

    you should apply the @Transactional annotation only to methods with public visibility

    Also, to use same connection you can set datasorce in context as SingleConnectionDataSource

    wraps a single JDBC Connection which is not closed after use.