5

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 ?

specializt
  • 1,881
  • 15
  • 25
Makoto
  • 735
  • 2
  • 15
  • 43

2 Answers2

3

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.

specializt
  • 1,881
  • 15
  • 25
1

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

Prasad Khode
  • 6,303
  • 11
  • 42
  • 57