Java JDBC Transactions

Su Suriya Ravichandran Updated 18 Nov 2026
15 min read ·Lesson 219 of 306

A transaction is a group of SQL statements that succeed or fail as one unit. Java JDBC transactions let you run several updates and then either commit them all or roll back every one of them, so the database never ends up half-changed.

Transactions matter whenever one business action touches more than one row: moving money between accounts, placing an order and reducing stock, or enrolling a student and charging a fee. In this lesson you will see what goes wrong without a transaction, control transactions with setAutoCommit(false), commit() and rollback(), see how other connections are isolated from uncommitted work, use savepoints, choose an isolation level, and build an order-placement method that is all-or-nothing.


What Makes a Transaction: ACID

Databases describe transactions with four properties, known as ACID.

PropertyMeaningExample
AtomicityAll statements succeed, or none take effectA transfer debits and credits, or does neither
ConsistencyRules such as constraints hold before and afterA balance never goes below zero
IsolationOther users do not see half-finished workNo one sees money that has left one account but not arrived in the other
DurabilityOnce committed, changes survive a crashA confirmed payment is not lost on restart

The JDBC Transaction Methods

MethodPurpose
setAutoCommit(false)Start managing transactions yourself
commit()Make all changes since the last commit permanent
rollback()Undo all changes since the last commit
setSavepoint(name) / rollback(savepoint)Undo only part of a transaction
setTransactionIsolation(level)Choose how much other transactions can see

The Problem: Auto-Commit Mode

A new JDBC connection is in auto-commit mode: every statement is committed as soon as it finishes. If a two-step operation fails between the steps, the first step stays in the database.

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AutoCommitProblem {

    static void transfer(Connection connection, String fromId, String toId, BigDecimal amount,
                         boolean failMidway) throws SQLException {
        try (PreparedStatement debit = connection.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?");
             PreparedStatement credit = connection.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
            debit.setBigDecimal(1, amount);
            debit.setString(2, fromId);
            debit.executeUpdate();

            if (failMidway) {
                throw new SQLException("Connection lost after debit"); // simulate a failure
            }

            credit.setBigDecimal(1, amount);
            credit.setString(2, toId);
            credit.executeUpdate();
        }
    }

    static void printBalances(Connection connection) throws SQLException {
        BigDecimal total = BigDecimal.ZERO;
        try (Statement statement = connection.createStatement();
             ResultSet rows = statement.executeQuery("SELECT id, owner, balance FROM accounts ORDER BY id")) {
            while (rows.next()) {
                BigDecimal balance = rows.getBigDecimal("balance");
                total = total.add(balance);
                System.out.println("  " + rows.getString("id") + " " + rows.getString("owner") + ": " + balance);
            }
        }
        System.out.println("  Total: " + total);
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:bank", "sa", "");
             Statement setup = connection.createStatement()) {

            setup.executeUpdate("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY, owner VARCHAR(30), balance DECIMAL(10, 2))");
            setup.executeUpdate("INSERT INTO accounts VALUES ('A-101', 'Asha', 5000.00), ('B-202', 'Ravi', 2000.00)");

            System.out.println("Auto-commit: " + connection.getAutoCommit());
            try {
                transfer(connection, "A-101", "B-202", new BigDecimal("1000.00"), true);
            } catch (SQLException e) {
                System.out.println("Transfer failed: " + e.getMessage());
            }
            printBalances(connection);
        }
    }
}

Output:

Auto-commit: true
Transfer failed: Connection lost after debit
  A-101 Asha: 4000.00
  B-202 Ravi: 2000.00
  Total: 6000.00

How it works:

  • The debit ran and was committed at once, because auto-commit is on.
  • The simulated failure stopped the method before the credit. Asha lost 1000.00 and Ravi received nothing.
  • The total money in the bank dropped from 7000.00 to 6000.00. This is exactly the kind of inconsistency transactions prevent.

Commit and Rollback in Java JDBC Transactions

Turn auto-commit off, run all the steps, then call commit(). If anything throws, call rollback() in the catch block.

connection.setAutoCommit(false);
try {
    // statement 1
    // statement 2
    connection.commit();      // all changes become permanent
} catch (SQLException e) {
    connection.rollback();    // every change since the last commit is undone
}
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CommitAndRollback {

    static void transfer(Connection connection, String fromId, String toId, BigDecimal amount,
                         boolean failMidway) throws SQLException {
        try (PreparedStatement debit = connection.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE id = ?");
             PreparedStatement credit = connection.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
            debit.setBigDecimal(1, amount);
            debit.setString(2, fromId);
            debit.executeUpdate();

            if (failMidway) {
                throw new SQLException("Connection lost after debit");
            }

            credit.setBigDecimal(1, amount);
            credit.setString(2, toId);
            credit.executeUpdate();
        }
    }

    static void safeTransfer(Connection connection, String label, String fromId, String toId,
                             BigDecimal amount, boolean failMidway) throws SQLException {
        connection.setAutoCommit(false);
        try {
            transfer(connection, fromId, toId, amount, failMidway);
            connection.commit();
            System.out.println(label + ": committed");
        } catch (SQLException e) {
            connection.rollback();
            System.out.println(label + ": rolled back (" + e.getMessage() + ")");
        } finally {
            connection.setAutoCommit(true); // restore the default for the next user of this connection
        }
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:bank", "sa", "");
             Statement setup = connection.createStatement()) {

            setup.executeUpdate("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY, owner VARCHAR(30), balance DECIMAL(10, 2))");
            setup.executeUpdate("INSERT INTO accounts VALUES ('A-101', 'Asha', 5000.00), ('B-202', 'Ravi', 2000.00)");

            safeTransfer(connection, "Transfer 1", "A-101", "B-202", new BigDecimal("1000.00"), false);
            safeTransfer(connection, "Transfer 2", "A-101", "B-202", new BigDecimal("500.00"), true);

            try (ResultSet rows = setup.executeQuery("SELECT id, owner, balance FROM accounts ORDER BY id")) {
                while (rows.next()) {
                    System.out.println("  " + rows.getString("id") + " " + rows.getString("owner") + ": " + rows.getBigDecimal("balance"));
                }
            }
        }
    }
}

Output:

Transfer 1: committed
Transfer 2: rolled back (Connection lost after debit)
  A-101 Asha: 4000.00
  B-202 Ravi: 3000.00

How it works:

  • Transfer 1 runs both updates and commits. Asha has 4000.00 and Ravi 3000.00.
  • Transfer 2 debits 500.00, then fails. rollback() undoes that debit, so Asha's balance is back to 4000.00 and the total is still 7000.00.
  • The finally block switches auto-commit back on. This matters when connections are shared or come from a pool.

Note: If a connection is closed while a transaction is still open, most drivers roll it back, but the JDBC specification leaves this to the driver. Always end every transaction with an explicit commit() or rollback().


Uncommitted Changes Are Invisible to Other Connections

Until you commit, other connections keep seeing the old data. This is the isolation in ACID. The example opens two connections to the same in-memory database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TransactionVisibility {

    static String balanceOf(Connection connection) throws SQLException {
        try (PreparedStatement query = connection.prepareStatement("SELECT balance FROM accounts WHERE id = ?")) {
            query.setString(1, "A-101");
            try (ResultSet row = query.executeQuery()) {
                row.next();
                return row.getBigDecimal("balance").toPlainString();
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        String url = "jdbc:h2:mem:shared_bank"; // a named in-memory database shared by both connections
        try (Connection writer = DriverManager.getConnection(url, "sa", "");
             Connection reader = DriverManager.getConnection(url, "sa", "")) {

            try (Statement setup = writer.createStatement()) {
                setup.executeUpdate("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY, balance DECIMAL(10, 2))");
                setup.executeUpdate("INSERT INTO accounts VALUES ('A-101', 5000.00)");
            }

            writer.setAutoCommit(false);
            try (Statement update = writer.createStatement()) {
                update.executeUpdate("UPDATE accounts SET balance = balance - 1000 WHERE id = 'A-101'");
            }

            System.out.println("Writer sees (before commit): " + balanceOf(writer));
            System.out.println("Reader sees (before commit): " + balanceOf(reader));

            writer.commit();
            System.out.println("Reader sees (after commit):  " + balanceOf(reader));
        }
    }
}

Output:

Writer sees (before commit): 4000.00
Reader sees (before commit): 5000.00
Reader sees (after commit):  4000.00

How it works:

  • Both connections use the URL jdbc:h2:mem:shared_bank. In H2, a named in-memory database is shared by all connections in the same program while at least one stays open.
  • Inside its own transaction, the writer sees its change immediately.
  • The reader still sees 5000.00, because the change is not committed. After commit(), the reader sees 4000.00.

Savepoints: Undo Part of a Transaction

A savepoint marks a point inside a transaction. rollback(savepoint) undoes only the work done after that mark, and the transaction continues.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class SavepointExample {

    static int countEnrollments(Connection connection) throws SQLException {
        try (Statement statement = connection.createStatement();
             ResultSet row = statement.executeQuery("SELECT COUNT(*) FROM enrollments")) {
            row.next();
            return row.getInt(1);
        }
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:school", "sa", "")) {
            try (Statement setup = connection.createStatement()) {
                setup.executeUpdate("CREATE TABLE enrollments (id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, student VARCHAR(20), course VARCHAR(30))");
            }

            connection.setAutoCommit(false);
            try (PreparedStatement enroll = connection.prepareStatement("INSERT INTO enrollments (student, course) VALUES (?, ?)")) {
                enroll.setString(1, "Asha");
                enroll.setString(2, "Java Basics");
                enroll.executeUpdate();

                Savepoint afterFirst = connection.setSavepoint("after_first");
                System.out.println("Savepoint: " + afterFirst.getSavepointName());

                enroll.setString(2, "Docker Mastery");
                enroll.executeUpdate();
                System.out.println("Inside transaction: " + countEnrollments(connection) + " enrollment(s)");

                // Docker Mastery turned out to be full: undo only that enrollment
                connection.rollback(afterFirst);
                System.out.println("After rollback to savepoint: " + countEnrollments(connection) + " enrollment(s)");

                enroll.setString(2, "Spring Boot");
                enroll.executeUpdate();
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }

            List<String> courses = new ArrayList<>();
            try (Statement statement = connection.createStatement();
                 ResultSet rows = statement.executeQuery("SELECT course FROM enrollments ORDER BY id")) {
                while (rows.next()) {
                    courses.add(rows.getString("course"));
                }
            }
            System.out.println("Committed courses: " + courses);
        }
    }
}

Output:

Savepoint: after_first
Inside transaction: 2 enrollment(s)
After rollback to savepoint: 1 enrollment(s)
Committed courses: [Java Basics, Spring Boot]

How it works:

  • The savepoint is set after the first enrollment. The second enrollment (Docker Mastery) comes after it.
  • rollback(afterFirst) removes only Docker Mastery. Java Basics stays, and the transaction is still open.
  • After adding Spring Boot, commit() saves both remaining enrollments. A plain rollback() at any point would still have undone everything.
  • releaseSavepoint(savepoint) frees a savepoint you no longer need. Savepoints also end automatically on commit or rollback.

Transaction Isolation Levels

The isolation level decides how much one transaction can see of others that run at the same time. Higher levels prevent more problems but allow less parallel work.

LevelDirty readNon-repeatable readPhantom read
TRANSACTION_READ_UNCOMMITTEDPossiblePossiblePossible
TRANSACTION_READ_COMMITTEDPreventedPossiblePossible
TRANSACTION_REPEATABLE_READPreventedPreventedPossible
TRANSACTION_SERIALIZABLEPreventedPreventedPrevented
  • Dirty read: reading another transaction's uncommitted change.
  • Non-repeatable read: reading the same row twice and getting different values because someone committed in between.
  • Phantom read: running the same query twice and getting new rows the second time.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class IsolationLevels {

    static String levelName(int level) {
        return switch (level) {
            case Connection.TRANSACTION_READ_UNCOMMITTED -> "READ_UNCOMMITTED";
            case Connection.TRANSACTION_READ_COMMITTED -> "READ_COMMITTED";
            case Connection.TRANSACTION_REPEATABLE_READ -> "REPEATABLE_READ";
            case Connection.TRANSACTION_SERIALIZABLE -> "SERIALIZABLE";
            default -> "NONE";
        };
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:bank", "sa", "")) {
            System.out.println("Default level: " + levelName(connection.getTransactionIsolation()));

            boolean supported = connection.getMetaData()
                    .supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE);
            System.out.println("SERIALIZABLE supported: " + supported);

            connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            System.out.println("New level: " + levelName(connection.getTransactionIsolation()));
        }
    }
}

Output:

Default level: READ_COMMITTED
SERIALIZABLE supported: true
New level: SERIALIZABLE

How it works:

  • getTransactionIsolation() returns one of the Connection constants, and the switch turns it into a readable name.
  • DatabaseMetaData.supportsTransactionIsolationLevel() checks support before you change the level.
  • Set the isolation level before starting a transaction. Defaults differ: H2 and PostgreSQL use READ_COMMITTED, while MySQL (InnoDB) uses REPEATABLE_READ.

Note: READ_COMMITTED is the right choice for most applications. Raise the level only for a specific transaction that needs it, because stricter levels can make transactions wait for each other or fail with serialization errors that you must retry.


A Reusable Transaction Helper

Writing setAutoCommit, commit, rollback and finally in every method is repetitive. A small helper takes the work as a lambda and handles the transaction around it.

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TransactionHelper {

    @FunctionalInterface
    interface SqlWork {
        void run(Connection connection) throws SQLException;
    }

    static void inTransaction(Connection connection, SqlWork work) throws SQLException {
        boolean previousAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        try {
            work.run(connection);
            connection.commit();
        } catch (SQLException | RuntimeException e) {
            connection.rollback();
            throw e;
        } finally {
            connection.setAutoCommit(previousAutoCommit);
        }
    }

    static void move(Connection connection, String sql, BigDecimal amount, String accountId) throws SQLException {
        try (PreparedStatement update = connection.prepareStatement(sql)) {
            update.setBigDecimal(1, amount);
            update.setString(2, accountId);
            update.executeUpdate();
        }
    }

    static void transfer(Connection connection, String fromId, String toId, BigDecimal amount) throws SQLException {
        inTransaction(connection, tx -> {
            move(tx, "UPDATE accounts SET balance = balance + ? WHERE id = ?", amount, toId);   // credit first
            move(tx, "UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, fromId); // may break the CHECK rule
        });
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:bank", "sa", "");
             Statement setup = connection.createStatement()) {

            setup.executeUpdate("""
                    CREATE TABLE accounts (
                        id VARCHAR(10) PRIMARY KEY,
                        owner VARCHAR(30),
                        balance DECIMAL(10, 2) CHECK (balance >= 0)
                    )""");
            setup.executeUpdate("INSERT INTO accounts VALUES ('A-101', 'Asha', 5000.00), ('B-202', 'Ravi', 2000.00)");

            for (String amount : new String[] {"1500.00", "9000.00"}) {
                try {
                    transfer(connection, "A-101", "B-202", new BigDecimal(amount));
                    System.out.println("Transfer " + amount + ": OK");
                } catch (SQLException e) {
                    System.out.println("Transfer " + amount + ": FAILED, rolled back (SQLState class "
                            + e.getSQLState().substring(0, 2) + ")");
                }
            }

            try (ResultSet rows = setup.executeQuery("SELECT id, owner, balance FROM accounts ORDER BY id")) {
                while (rows.next()) {
                    System.out.println("  " + rows.getString("id") + " " + rows.getString("owner") + ": " + rows.getBigDecimal("balance"));
                }
            }
        }
    }
}

Output:

Transfer 1500.00: OK
Transfer 9000.00: FAILED, rolled back (SQLState class 23)
  A-101 Asha: 3500.00
  B-202 Ravi: 3500.00

How it works:

  • inTransaction() saves the current auto-commit setting, runs the work, and commits. On any SQLException or RuntimeException, it rolls back and rethrows, so the caller still learns about the failure.
  • The CHECK (balance >= 0) constraint is a database rule that protects consistency.
  • For the 9000.00 transfer, the credit to Ravi succeeds first. The debit would leave Asha at -5500.00, so the database rejects it with SQLState class 23 (integrity constraint violation). The rollback also undoes Ravi's credit, so both balances stay at 3500.00.

Real-World Example: Placing an Order in One Transaction

Placing an order touches three tables: it creates the order, reserves stock for each product, and records each order line. If any product is short, nothing at all should change.

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map;

public class OrderService {

    static int placeOrder(Connection connection, String customer, Map<Integer, Integer> items) throws SQLException {
        connection.setAutoCommit(false);
        try (PreparedStatement insertOrder = connection.prepareStatement(
                     "INSERT INTO orders (customer, total) VALUES (?, 0)", Statement.RETURN_GENERATED_KEYS);
             PreparedStatement findPrice = connection.prepareStatement("SELECT price FROM products WHERE id = ?");
             PreparedStatement reserveStock = connection.prepareStatement(
                     "UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?");
             PreparedStatement insertLine = connection.prepareStatement(
                     "INSERT INTO order_items (order_id, product_id, quantity, line_total) VALUES (?, ?, ?, ?)");
             PreparedStatement updateTotal = connection.prepareStatement("UPDATE orders SET total = ? WHERE id = ?")) {

            // 1. Create the order header
            insertOrder.setString(1, customer);
            insertOrder.executeUpdate();
            int orderId;
            try (ResultSet keys = insertOrder.getGeneratedKeys()) {
                keys.next();
                orderId = keys.getInt(1);
            }

            BigDecimal orderTotal = BigDecimal.ZERO;
            for (Map.Entry<Integer, Integer> item : items.entrySet()) {
                int productId = item.getKey();
                int quantity = item.getValue();

                // 2. Reserve stock only if enough is available
                reserveStock.setInt(1, quantity);
                reserveStock.setInt(2, productId);
                reserveStock.setInt(3, quantity);
                if (reserveStock.executeUpdate() == 0) {
                    throw new SQLException("Not enough stock for product " + productId);
                }

                // 3. Record the order line at the current price
                findPrice.setInt(1, productId);
                BigDecimal price;
                try (ResultSet row = findPrice.executeQuery()) {
                    row.next();
                    price = row.getBigDecimal("price");
                }
                BigDecimal lineTotal = price.multiply(BigDecimal.valueOf(quantity));
                orderTotal = orderTotal.add(lineTotal);

                insertLine.setInt(1, orderId);
                insertLine.setInt(2, productId);
                insertLine.setInt(3, quantity);
                insertLine.setBigDecimal(4, lineTotal);
                insertLine.executeUpdate();
            }

            // 4. Save the total and make everything permanent
            updateTotal.setBigDecimal(1, orderTotal);
            updateTotal.setInt(2, orderId);
            updateTotal.executeUpdate();

            connection.commit();
            System.out.println("Order #" + orderId + " placed for " + customer + ", total " + orderTotal);
            return orderId;
        } catch (SQLException e) {
            connection.rollback();
            System.out.println("Order for " + customer + " failed: " + e.getMessage() + ". All changes rolled back.");
            return -1;
        } finally {
            connection.setAutoCommit(true);
        }
    }

    static int count(Statement statement, String table) throws SQLException {
        try (ResultSet row = statement.executeQuery("SELECT COUNT(*) FROM " + table)) { // fixed table names only
            row.next();
            return row.getInt(1);
        }
    }

    public static void main(String[] args) throws SQLException {
        try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:shop", "sa", "");
             Statement setup = connection.createStatement()) {

            setup.executeUpdate("CREATE TABLE products (id INT PRIMARY KEY, name VARCHAR(40), price DECIMAL(10, 2), stock INT)");
            setup.executeUpdate("CREATE TABLE orders (id INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, customer VARCHAR(30), total DECIMAL(12, 2))");
            setup.executeUpdate("""
                    CREATE TABLE order_items (
                        order_id INT REFERENCES orders(id),
                        product_id INT REFERENCES products(id),
                        quantity INT,
                        line_total DECIMAL(12, 2))""");
            setup.executeUpdate("""
                    INSERT INTO products VALUES
                    (1, 'Wireless Mouse', 799.00, 10),
                    (2, 'Mechanical Keyboard', 3499.00, 2),
                    (3, 'USB-C Cable', 299.00, 25)""");

            Map<Integer, Integer> ashaCart = new LinkedHashMap<>();
            ashaCart.put(1, 2); // 2 mice
            ashaCart.put(3, 3); // 3 cables
            placeOrder(connection, "Asha", ashaCart);

            Map<Integer, Integer> raviCart = new LinkedHashMap<>();
            raviCart.put(3, 5); // 5 cables: available
            raviCart.put(2, 3); // 3 keyboards: only 2 in stock
            placeOrder(connection, "Ravi", raviCart);

            System.out.println("Stock now:");
            try (ResultSet rows = setup.executeQuery("SELECT id, name, stock FROM products ORDER BY id")) {
                while (rows.next()) {
                    System.out.println("  " + rows.getInt("id") + " " + rows.getString("name") + ": " + rows.getInt("stock"));
                }
            }
            System.out.println("Orders: " + count(setup, "orders") + ", order lines: " + count(setup, "order_items"));
        }
    }
}

Output:

Order #1 placed for Asha, total 2495.00
Order for Ravi failed: Not enough stock for product 2. All changes rolled back.
Stock now:
  1 Wireless Mouse: 8
  2 Mechanical Keyboard: 2
  3 USB-C Cable: 22
Orders: 1, order lines: 2

How it works:

  1. One transaction for the whole order. Auto-commit is switched off at the start. Nothing is visible to other users until the single commit() at the end.
  2. Stock is reserved safely. UPDATE ... WHERE id = ? AND stock >= ? reduces stock only when enough is left. A return value of 0 means the product is short, so the method throws.
  3. Asha's order succeeds. Two mice at 799.00 and three cables at 299.00 give 1598.00 + 897.00 = 2495.00. The order, both lines and both stock changes are committed together.
  4. Ravi's order fails halfway. The 5 cables were already reserved and the order header already inserted when the keyboard check failed. rollback() undoes all of it, so the cable stock is 22 (25 − 3 for Asha), not 17, and Ravi's order row never becomes visible.
  5. Totals are exact. Prices are BigDecimal, and multiply() and add() keep two decimal places, so no rounding errors creep into the order total.

When a transaction inserts or updates many rows, sending them one at a time is slow. The next lesson shows how to send them in groups: Java JDBC Batch Update. To review the connection methods used here, see Java JDBC Connection, and for the safe SQL in every step, see Java JDBC CRUD.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java JDBC Transactions and get answers drawn from it.

Signed-in readers only.