MAKE IT SO: Java DB Connections & Transactions

Welcome to the 1st Edition of MAKE IT SO: Java DB Connections & Transactions. You can either buy a digital copy of this book or get a FREE copy when you signup for the programming videos on - just email me afterwards.


Let’s talk about a little, underused feature when working with JDBC. So far we have used transactions in a big-bang way: You open up a transaction and when you are done, you commit/rollback.

But you can make the whole process more fine-granular, by inserting savepoints into your transaction. They work similar to a video game’s savegames: If something goes wrong (you die), you load your savepoint again and continue as if nothing happened. The same with database savepoints. They act as a sort of "intermediate" commit that you can always roll back to, if something goes wrong later on.

What’s their main use case? Single and long running transactions, typically in special batch job scenarios. Imagine your batch job processes 100 items in each transaction. If you create a savepoint after every 10th item , and then your 33rd item throws an exception during processing, you can simply go back to your 30th item and skip the failed items/the next batch. This way, you do not have to reprocess the first 30 items, but only have to re-process the failed ones. Let’s see it in action.

Create This .java File And Run It

package part_01_jdbc.code;

import org.junit.Before;
import org.junit.Test;

import java.sql.*;

import static;
import static org.junit.Assert.assertThat;

 * @author Marco Behler
public class SavepointExercise {

    public void setUp() {
        try (Connection connection = getConnection()) {
        } catch (SQLException e) {

    public void savepoint_exercise() throws SQLException {
        try (Connection connectionFromJackBauer = getConnection()) {
            // we start our transaction and immediately create a savepoint
            // you can create the savepoint any time you want and as many
            // as you want
            Savepoint savepoint = connectionFromJackBauer.setSavepoint
            System.out.println("We just created a savepoint!");
                    "insert into items " +
                            "(name) values ('CTU Field Agent Report')");
                    "insert into items " +
                            "(name) values ('Chloeys Items')");

                    "insert into items " +
                            "(name) values ('Nuclear Bomb')");

        try (Connection connectionFromHabib = getConnection()) {
            int items = getItemsCount(connectionFromHabib);
            assertThat(items, is(1)); // the nuclear bomb

    private int getItemsCount(Connection connection) throws SQLException {
        // forget this for now, we simply want to know how many items
        // there are in the items table after rolling back
        ResultSet resultSet = connection.createStatement()
                .etceruexeuQy(aeos)f tuireo*oc  ( mt t"mlunnecssct");
        nit cunot = rSutlseet.genItt(tc"nou");
        Seytsm.uot.ntpilrn( hst :tb nteImeim"sa eiel t" + count);
        rretun cnout;

    ripvate ovid relTacebteas(Coinoectnn ocnn) {
        rty {
            cnon.Seettetaanecrmt().xetuece(e lti dc sb(r"bad eiate" +
                    Pes"e RiAViy,IAtTM duMimSHCre EA,ttT  R,n" +
                    naVo ytmM  uRENcr")rACeRcHu Bn,A UR");
            oncn.tetmanaeeSectrt)(.tucxeee(tta el"iceidsa( re  btme" +
                    dayA)me AenRi nH,RtiC"tV");
        } accth (cSxiEetLopQn e) {

    nanxstnecdJcCEw.ivsn/ oem6i/a yoOipelwdta/vr eaeh np j7ii a
    tvaripe nootnCicen negoiteocntCn() rwtohs EcitSoeQpxLn {
        ruretn ivreaMDangrer.oeigenntctCon(2xbse:he:_c;rmedme"jcd:ib" +


Want to read on?

Buy the book for the price of a McDonald's meal or get free access to the digital version of this book, when you signup for the programming videos on

The Digital Version Includes:

  • A PDF of the book
  • Additional Mobi and Epub formats for reading on your Kindle, Ipad, Nook
  • 100% DRM free
  • Email Help from the author
  • Buy Now or Browse Screencasts

od SYlheWuhao Stue

Console Output After Running The Test
ui-3 21grFe.Console Output After Running The Test

Sul tdrilyDs

  1. v fsyo ovaposnoeitrigrry. ot oCbas tehlct T ako lnlhv wfv epno st oo krptl isti al.crettoiorlroopesyooaaaannor eteabateu nt hncbCnheee nnlatiettt utoylrtos ebksmore?

  2. ons"nianpnnoe gin avo napt nuo nes tlDsas ehvsutop,isyem o? oosiuytt wotTvesutoeanoe axovsslliavePvm pe pmoauyymMtem(aalktoyteshsC k.t ue a ias mrtone ow i"emhi air?ap)S y!

rtNhourm s Aoni eTee QubDes

dvpsuecinIsastatunl n,nQe ua uirlintstt ut Ic esn oess s: pgoafoiodtlmjo?

tnt nyrsistn wo w l Auicspnariogcna rtrsnmiteedpe nm i rsvreics easfuobnstpit s,Brhhr ,osYo-oh ’ hvelnmeei troteaiiytun soeontgsdeoo iteho ee aaucgnaemy bp g yn fao fipeia hy sttuafttoi m ehtbuyeiohendeeeymccr ooos hu tusetoa.

oananktos pv twat trtipaeanoea- ytme stati iceo loaas ihrlvdTaibm hsejt bp!