Java · Advanced level

Advanced level · Module 3: Databases with JDBC · Lesson 4 of 4

Transactions and the Repository Layer

Group related changes into transactions, roll back on failure and keep database code behind repository interfaces.

In this lesson you will

  • Use transactions with commit and rollback
  • Implement a repository interface backed by JDBC and test it

Key concepts

transactioncommit and rollbackatomicityintegration test

The lesson

A transaction groups several changes so they succeed or fail together. Booking an appointment might insert the appointment and update a slot as taken; if the second step fails, the first must be undone. Call setAutoCommit(false), run the statements, then commit(), or rollback() in the catch block.

Keep transaction boundaries in the service or repository method that represents one business operation. Never leave a connection with an open transaction.

Because the service depends on a repository interface, you can keep unit tests fast with a fake repository and add a smaller number of integration tests that run the JDBC implementation against a real test database.

Step by step

  1. Write a bookAppointment method that performs two inserts.
  2. Wrap them in a transaction with commit and rollback.
  3. Force the second insert to fail and check nothing was saved.
  4. Write an integration test for the repository.

Practice activity

Complete the practical activity: switch the library project to a JDBC repository with transactions, keeping the service tests unchanged.

Expected result: The service tests still pass with the fake repository, and the new integration tests pass against the database.

Check your understanding

  1. What does rollback() do?

    Show answer

    It undoes all changes made in the current transaction.

  2. Why keep a fake repository for service tests?

    Show answer

    Service tests stay fast and independent of the database, while integration tests cover the real database code.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.