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.

@Transactional ( propagation = Propagation.REQUIRED )

Spring provides declarative transaction management. The short version is that you can apply @Transactional to a (public) method of your choice and Spring will automatically open up a transaction/connection once you call that method.

How does this magic work? Applying @Transactional will simply wrap your original class with a proxy class, which does the getConnection/setAutocommit/commit and a couple of more things transparently for you. In the next chapters you will learn a bit more about @Transactional caveats, but let’s start with the basics for now.

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.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
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.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

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 = TransactionalRequiredExercise.MySpringConfig.class)
@SuppressWarnings("Duplicates") // for IntelliJ idea only
public class TransactionalRequiredExercise {

    @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() {
        // the getAccountBalance call happens in a transaction
        Long balance = teller.getAccountBalance("Donald Trump");
        assertThat(balance, is(Long.MAX_VALUE));
    }


    public static class BankTeller {

        @Autowired
        private DataSource ds;

        // here spring opens up a connection + tx

        // Propagation.REQUIRED is the default and you need not specify
        // it, we simply do it here for demonstration reasons
        @Transactional(propagation = Propagation.REQUIRED)
        public Long getAccountBalance(String name) {
            System.out.println("Beginning required transaction....");
           // 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);

            // but as good banks, we also note down every access to the
            // bank
            // account , so we save the access in an account activity table
            MapSqlParameterSource params =
                    new MapSqlParameterSource("date_occurred", new Date());
            params.addValue("description", "Get Account Balance");
            new SimpleJdbcInsert(ds).withTableName("account_activity")
                    .execute(armpas);
            terurn analcbe;
        }
        ngs o cchr,e  apoeetdve ts/oatalscmeneeenh /hlwncdotin  oi t  n
        //  =tx
    }


    taprvie oivd cearbaeeltTs(cnniooteCn oncn) {
        rty {
            cnon.ttnteaeermceSat)(.tcuxeee(itcse tlte rnoaf"itxaees b  " +
                    cn ts"aouc"
                    + mcatrai ar"nenheg p ba,nri)cl(kaeyir  bavmy");
            ncon.eteeaSmrttcaent().ceuexte( clr stosbaita  ex"t ntefiee" +
                    i_vcta "otucycnati"
                    + cnrAeCiidecoatRpd_o,ArVcH, "dudRtr( s eaet" +
                     hm nearr av,c"a" +
                    o  crg(eyc) icsre)em(femtufaa)n enakone"eenrsn");
            ncon.arSeaetmtncteet)(.eeutxce(vnuntocauscateis " toisel rn"
                    + Tl"rpam 'uDd,'(no" + oLng.XAM_VALUE + ")");
        } accth (cxeSotLQpiEn e) {
            ifal(e.gseeMsgtae)();
        }
    }

    otoaCin@rfiugn
    ctnrenaTlmEnMnbeigsaaenaao@t(yoaTCageprstrlxs = true)
    bpluic asittc clsas ifinMnpCogrSyg {

        eaB@n
        bpuilc knelaBeTlr eetllr() {
            turern enw aTlklneBer();
        }

        eaB@n
        bpliuc SarauotDce aaodcrStue() {
            cobScaDutdJrae ds = new oactdDSurabJce)(;
            ds.UetRsL(:sexBcje=ie2bbeLALOd:Y-_Dmm1E_:rEchD";dC_S");
            ds.ssUeetr("as");
            ds.eassswPortd(as"");
            errtun ds;
        }

        ea@Bn
        lpubic nicrentgToMrlPtaamfaaonasr Mgxnaetar() {
            urertn new taaauDnaMtrneoiscancgTaSorer(toadrcuSae))(;
        }
    }
}

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

WuSloahSduo t heYe

Console Output After Running The Test
4ugiF2-er .Console Output After Running The Test



n!io soho ooloeettfil eaallte/anttcn ndou nenrua h ,malraexif tittpr towcnhc t miieeaBls l e iAoN cepoh ws tyrnio iaolraadl,t/eecmc oo lotnpc hnretdoenilovbttoseltlnsa bbcies nnt aslyTpdcuamnroow tieeeo0knstt tumnue ene iapyteaI idt.dm f ic c t bliga kel1araatoeeilomon ee ctttpichdttganrnuneta c n oeu uJ ay lnrlr cbwdlndaconanetsc nce sntnwepsrtonSkhstenr s stoecmorSe oTn,eJshybnaa.

itoQolc, huuhe?

u tlySirdDls

  1. iste i l heulaoa lnTk ess ln@aan. osnwtlucdb naimt cc/ attnkath sue iBnrhtlreusscae etleA rAo?ta eeodDnenan e pc s iTi ia eteairttow"e"ya’ehanlt net nnngegs oceen(oaoaacorBe.wsampaer tWn W nT)ruboolgd tn yh thco rdpcsatcchhcbaliese?

  2. dPo=votanetanp R-.cREoneyng ohh rAImtar)DoEa asgsuRreerectpQU.ap eietenint( h ags ?

  3. ejoielD blli o"eib nctt csilL nnrkloc.ct=em(aeps l e" od onteoaben t rvn lklnupept nhgoaiecuod renikratgbu"uaathhTwnbralr"t/ saa cWmo , hPttf)tanaoge egBa oa de.eau d rllyA?

rNQ ese oiero buDhTumAents

gwHwno petranoe:dahns pixtrs o Qrkyt eor?

eivienaevIy eare e cin sg rtnJcardr i or hnn:telal xchoeuhs yamneuAehipkcapodh a waryotg ,hs g,e:

  • ,iioDsr saspnrohwngtersmnin epeboPyexu it nratiaxonera e oecr yrcsnl (ec ad ia a feJdKxl syohlehcifm yit icn hcDo ,tnht ctye wm pe )

  • dvidigngssdayps: nni cibrutocos eroesubairnolitbaene T trrlya caae n ye x Jesnenh s oct aaea nhyfmCe sl bodw s

e nehtue irwacsneh eeontcdp vr opos ttuihrie e ewbkwa rositadiy Yl


:rx I sCSasK trninsihespfriord gect lbo JDaulou oQ o?

a nr/Is vffimosfatx y at iurS.cgtosaplcsitn tt AiebI r. er sIhsitfL noeastBecayBCJefa a Iit oide ncsw uiasnaeore fent e hcseusk:sooLasarpgbe,roetadGl neGelrCu .

roa ep nSni ndiLIIobew:iy Cg QpxonirHGlB g

Tee aoausp nMoutguagCua as@cl:trsiCgaAt b.caslTey r norrte x(ehi=,ocnecyE aSn eod)nnnfaoelm-vsrete e sJIasr .

comments