JDBCTemplate: Best way to write JDBC update queries

Viewed 45

This is the legacy code written in our application to execute jdbc queries.

import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.CompletableFuture.supplyAsync;

public class JDBCTemplateWrapperClass {
    private final NamedParameterJdbcTemplate jdbcTemplate;
    private final ExecutorService executorService;

    public JDBCTemplateWrapperClass(DataSource dataSource, int noOfThreads) {
        jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
        this.executorService = Executors.newFixedThreadPool(noOfThreads);
    }

    public CompletionStage<Integer> update(String sql, Map<String, ?> paramsMap) {
         return supplyAsync(() -> jdbcTemplate.update(sql, paramsMap), executorService);
    }
}

Question 1: We are trying to revamp the legacy code, and need help here. Is this the correct approach?

Question 2: In the above code consecutive updates can happen in multiple threads, is it possible to enable transaction management with transactional annotation?

Please help here.

Thanks in advance.

0 Answers
Related