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.

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
 */
@RunWith(SpringJUnit4ClassRunner.class)
@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;

    @Autowired
    private PlatformTransactionManager txManager;

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

        // and our tx manager who
        assertNotNull(txManager);

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


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

        aB@en
        lubpic actauSroDe docSutraae() {
            aubaDotcJdcrSe ds = new aDuSdbrcaJctoe();
            ds.tseURL(=Oe2dcY_DbDB__smxS-L;CLm:"hEEebA:jd:ric1ee");
            ds.estseUr(sa"");
            ds.tasrwePssod(s"a");
            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
        aeB@n
        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 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

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 aagTwse.bar 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)

comments