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.

Spring - Creating a DataSource and TransactionManager

Fundamentally there is not a big difference when using Spring to access databases as compared to plain JDBC. You still need your DataSource, but Spring also introduces the concept of a "PlatformTransactionManager". The transaction manager’s job is to know how to, well, open, close and keep track of running transactions. (And later on, to alleviate us from the pain of calling setAutocommit(false) etc. manually)

In this example we are using a plain DataSource transaction manager and you will encounter other ones in later chapters.

Create This .java File And Run It

package part_03_spring.code;

import org.h2.jdbcx.JdbcDataSource;
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.datasource.DataSourceTransactionManager;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

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

import static org.junit.Assert.*;

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

    private static final TransactionDefinition TX_DEFAULTS = null;

    @Autowired // feel free to use @Inject here instead
    private DataSource ds;

    private PlatformTransactionManager txManager;

    public void exercise() {
        // and can get connections
        try (Connection connection = ds.getConnection()) {
            System.out.println("Yay, we have an open connection");
        } catch (Exception e) {

        // and our tx manager who

        // spring's "low-level" way of programmatically opening up tx's...
        TransactionStatus transaction =
        Seytsm.uot.lnrtipn( !  ri atonocnoep"ntanaAnsndw");
        ./na dol s./cn.ig

    a-pufrsnvo r/na /icjgio g
    lpibuc tsiatc aslcs CfMnySporniigg {

        lubpic actauSroDe docSutraae() {
            aubaDotcJdcrSe ds = new aDuSdbrcaJctoe();
            utrern ds;

         temt,enan rd sac s/rfsffe  errohoiarnirneeaii g/tfnfedtt
        .rc   itarngteoi.t  hrasae iae f.wpBaneu( )c/nlsi boiu e/ eesrn
        ec/etrelady en,oh ocar  /  anednaue phwsi eeln
        tgDrc/rT/McsaSeoo ataaanenanuir
        ilubpc tmTaeoisatlcanfgnnPMaorrar gnxetaMar() {
            rtuern enw urSDanttcaaiearcaToMnsgeoanr(uorScaadte)();

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

t WhYlu Sae hSudooe

Console Output After Running The Test
e-F4rgiu 1.Console Output After Running The Test

dtulDyrilS s

  1. grieaoSrpntCh adii g:/osfsnpw pwge/onmgg/ h-wnengrr rofa u.n Sr m aott/oracsed-aagrnt/tsfesketloheo tnoiwe--eeIgsiv onnreo stiarns eartvwighdrt t helasaftoagts /e oandlop/ tot , reproici w-rryderctniJ/n.cstiv wrir:us an nhfpt.ourt hh maaic- nkpcl

  2. da aew p ap pFnsllSsty ota gniXhaithrb t.atitla e( ocslcsDaetteoynvRsoTTa ncglem xut rrT sei msLiJehEclrgto jc il Afrayepnuanssd)ia,hhtavn oi pieo n ca e abtscaepu _ oUen s aaana lnnhoils eaundrdDndpvboeiusIa rt’n eed.

  3. ntRnattohncee e odfoeginptyno uf iIweehtta.aa Anit iin@@ihjAeh tatttencr woln ndr?

eDm nebh tosQriu uNeToAe rs

elonoactnd i auQrnernaSsia awh ge roopnctD sednac soaTrtae:tMooHncestsa?

edwvllotpenclsp:Ilbo le as,nuh aruiiho iow fc to hi Ajt hev ey boflaatdbs :

l ntllg.uC)et)yielrnAognicSead(banrctse rm othde,tDUaii( svmn fc ,t er hct.asve Tfsid iouarter itoneactaws as aosio anoattatoms uoejenc inle,.

hnaotbero cndQyianenrodg yMt ew irttWs aysh :antwaeaaaacTn?

Tnasseiete oT ehmeis ha t nae nrweomnrfiriieea ehhiagra ron s,r)u a"!aah oioH qulauct’aarft nnpt(itd cnAsnesirnern’t era o rsd vd:t tatotoh:oiytdn cseawoe -ilnlyeoeMnngn ncoobdseatpti iuaowhyct pm l siTtnahkeii:nlpNpil alttwe"cn vxae rnl boh gktlt nnaaockcihsYiaAernaneogoncrtS. st wadctag e-e ooras yaadma Sw nhnlezlnnaa. tt ,aepa afle aih ayMrbue attglrmiiscaiu)