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 marcobehler.com - just email me afterwards.

Programmatic Transactions with Spring

So far we have only been using the @Transactional annotation. In Spring-land this is called the "declarative" approach to open up transactions. There’s also the programmatic approach, where we don’t use any annotations, proxies etc. Rather we open up our transaction directly through code.

Spring offers us TransactionTemplate classes for this, or using the PlatformTransactionManager directly.

Let’s see what that looks like in practice:

Create This .java File And Run It

package part_03_spring.code;

import org.h2.jdbcx.JdbcDataSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * @author Marco Behler
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
        classes = ProgrammaticSpringExercise.MySpringConfig.class)
@SuppressWarnings("Duplicates") // for IntelliJ idea only
public class ProgrammaticSpringExercise {

    @Autowired
    private BankTeller teller;

    @Autowired
    private DataSource ds;


    @Before
    public void setUp() {
        try (Connection connection = ds.getConnection()) {
            createTables(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void exercise() throws SQLException {
        Long balance = teller.getAccountBalance("Donald Trump");
        assertThat(balance, is(Long.MAX_VALUE));
    }


    public static class BankTeller {

        @Autowired
        private PlatformTransactionManager txManager;

        @Autowired
        private DataSource ds;

        public Long getAccountBalance(final String name) throws
                SQLException {
            Long balance = new TransactionTemplate(txManager).execute(
                new TransactionCallback<Long>() {
                    @Override
                    public Long doInTransaction(TransactionStatus status) {
                        System.out.println("This time we open up a " +
                                "transaction with a TransactionTemplate");
                        // let's return the balance from a database table
                        Long balance = new JdbcTemplate(ds).queryForObject(
                                "select balance from accounts " +
                                        "where name = ?", Long.class, name);
                        System.out.println("The balance for : " + name +
                                " is:" + balance);
                        return balance;
                    }
                });

            // or instead of using the transaction template, you could
            // use this to open and close tx
            //
            // TransactionStatus tx = txManager.getTransaction(null);
            // TODO how do you commit? :)
            return abancle;
        }

    }


    rtipvae ovid rlatTeecabes(Cooctinenn nocn) {
        rty {
            conn.ataSettcnermeet().eextcue(re  e tli e"xaonfatcsitse tb" +
                    aa"vcci tnctuit_yo"
                    + d_rr(d,e"r,Hcc_aaoA euARdothCtlV uaRodntee cc" +
                    AeHtRdi oci)Vp ACr"Rsn");
            conn.taaneSteretemct().tuxeece(e et tt "cnasaboxslrteiie  f" +
                    cct"sua no"
                    + prye,ann agy c ) krrvht ca"n(bbaalriieimmea");
            oncn.actameStenteret().xtuecee(sulotes aetosnuiv "tnca crni"
                    + DT"l'orp(dua, mn'" + Long.XVL_MAAUE + ")");
        } tccah (LxtiocpeQSEn e) {
            aifl(e.eeatggssMe))(;
        }
    }

    C@oifgatironun
    anlansebrnnamgaiEaMentTe@cot(yaoeprtCsgraTlxs = ture)
    plbuic stitac calss SgfniponMrCiyg {

        ea@Bn(mane = aTkbnrlle"e")
        iblpuc aTnleBkler tleler() {
            rrtuen new ellkeaTBnr)(;
        }

        aBe@n
        bluipc cSDatoaure cautoSdare() {
            arcoucJDaSdtbe ds = enw urDbSocaJadcte();
            ds.sUeRtL(cDeO_Sedc-x2;YsELmedb:CDLjh:=AmEBe"i_r:_b1");
            ds.ssUeter(as"");
            ds.rstsesPoawd("as");
            tuerrn ds;
        }

        @Baen
        iulbpc cfanrnPooiatTgnmetlaaMsrar gMnexatar() {
            rturen new arncotTucarnaaDeaangSsitMeor(atudroaSce))(;
        }
    }
}

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 marcobehler.com

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

dhWul taS ouheYS oe

Console Output After Running The Test
7e-g ru4Fi.Console Output After Running The Test



lDdriutSly s

  1. e .csmusssnimcroaoat=t it aexn tUhaei oiians eTmo.caiggiancnto p ni ntewn" b ydtdiIta ms"atte tah a pSisrtttitn s rrmmticattho otgtTeanerhlpa ieraah hah notes eottcnntelswa rnvm nostunr.

  2. c ’lte eCsIlmcTou arRWeonaa ks e ysieacttaoarete.gpn naotTii l dhgtrcctsa< enks la oh.ushal an dda rTtletCiaL. lWrnoadanwoesenibi >sndet teo salibsthffUuh?

  3. tctl aaoomacaeurnoncsdogroatnir gamnait egn n m enpairpiituiodmc taf mepnshRetifn

hereoeDt Nieu Abnour m TsQs

eomntn@mrluuovtapmrdocnitnn W oasn loaaen geigtser ahinc ot r cnotQa ataIia h:sanmaeTssr?

iir cnAh ncaSalomio u pDotteetTnciorofm:fgt ief :

hmyioi qndaebuhtaIasir rctp gssrnaaresarrmeo sc a cuiwianaatia x prees Fyemse ntaan aocn,dllu.mih t,mest atne flx oih tp eo smi aoe rl ritiueoeubcytcrape e oaroTn opnrtssiy a iatsoune sl ia iig ng s nsn t doa,inholpuntepfsi tcomrni.mefnxmnonhestg adaocoacnoctohcaes e omp pss oy inayytamcgag tcernarngT noylm ctnnero ha otao etrmao tit ere gi v alt tegeuiladmlrt o banyphahtaaim awfaaaeln nnttBumooen eclta vlingep ohpsi tnlctatt oribtnao o oaon o irnlhnp yapsypuagrnsulrS cyotu ira.obpaoegraenatetaash toaenio ltgPt.

a iyvfotgeretststuhteuelgancgodcincaninhl n aleotodsuol ehnndit a aaotWei ,nel Scmnr sa, a s uthateeoatnid in uh eiutt wodkegsa rcImnumsrmo nnner rtser rttd, r uJ tpo,cchieo eaharafos.tiorTeao nooheirtvies p,e.rnaoeaitrlanimlmetitfuEBneaimheiru tsnrsF fsbeghfarna iom nMl awniaoOdkitfai tr sleyntrstnnituwccgaachpcitc s g cy oCn atoosnue lanrafp gpag.


rhao rtegnattuec i:acdn aan uamPlforsn eeir pcdlsorgs Tts IoliTe rnSetmaulnsfigovTQrr ayMeheitnp?

liiminatdrgctnacfoge TacAoeartin mootu: hnfpei i fo S :

g hc Thnra ct rTraa iotecal nes mctntesh tixslooupT ntl Tcgea mI itgneapiafasoar inleTeJamds eii.hconeo taPAagmcTepmd eiegpmsindhnrpaamonecay mtorrenne srme gnAsoot snm, cSal tsesthee igtnr ismnlasualeprhriUbhorour.

comments