Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do I need a connection.commit() after executeBatch()?

I have to check the code of a fellow coworker and I stumble on this piece of code:

private void pdate(JdbcTemplate jdbcTemplate, List<Long> saisineIdsToUpdate,Connection connection) throws SQLException {
    String sqlUpdate = "UPDATE SAISINES SAI WHERE SAI.IDSAISINE = ?"; //request simplified

    PreparedStatement psUpdate = connection.prepareStatement(sqlUpdate);

    for (Long saisineId : saisineIdsToUpdate) {
        psUpdate.setLong(1, saisineId );
        psUpdate.addBatch();

    }
    psUpdate.executeBatch();
    psUpdate.close();

The code works, the updates are done correctly, but I cannot find the trace of a connection.commit(); I wonder how it can work without the commit - could someone explain why ?

like image 549
Makoto Avatar asked Sep 29 '22 10:09

Makoto


2 Answers

As explained here, JDBC-drivers commonly use autocommit, you can enable database-traces via DBMS-driver specific settings like showSQL or generateDDL in JPA.

To enable manual- transaction support instead of the auto-commit mode that the JDBC driver uses by default, use the Connection object's setAutoCommit() method. If you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass a boolean true to turn it back on again.

like image 171
specializt Avatar answered Oct 05 '22 06:10

specializt


if you set auto-commit on your connection object to false then we have to commit the transaction manually

connection.setAutoCommit(false);
// your code goes here
connection.commit();

if you don't set auto-commit then default its value is true and it will commit each record

like image 43
Prasad Khode Avatar answered Oct 05 '22 06:10

Prasad Khode