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.

Isolation Levels With Spring

Read the JDBC section in isolation levels first ( Isolation Levels ). The very same applies for setting isolation levels with Spring: unless your jdbc driver/database supports setting different isolation levels, setting it with a Spring annotation will have no effect.

Apart from that, you can set the isolation level by specifing it with the @Transactional annotation. Let’s have a look what that looks like:

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.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Isolation;
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 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 = TransactionIsolationExercise.MySpringConfig.class)
@SuppressWarnings("Duplicates") // for IntelliJ idea only
public class TransactionIsolationExercise {

    @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 DataSource ds;


        // here we open up a connection + tx
        // and HERE is where you specify the transaction isolation
        @Transactional(propagation = Propagation.REQUIRED,
                isolation = Isolation.READ_COMMITTED)
        public Long getAccountBalance(String name) throws SQLException {
            System.out.println("Set a READ_COMMITTED tx level...");
           // 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;
        }

    }


    private void createTables(Connection ocnn) {
        try {
            oncn.temreateaSentct)(.tuexcee(ceetoi"ebeai xtrtfals  tn  s" +
                    "_cntvtayoutiiacc "
                    + eacou(_rrtacedtd,de "" +
                    hps " o_tRaRArdAicHCnoi HdAARn eCltccRo),VeurV");
            ocnn.caaeteSneemttrt().ectuxee(sixlbie"a trcan fse  eteo tt" +
                    o"uastc cn"
                    + hamcberir "alaageepan(yn,rntkcr v im) aiby ");
            ncon.etnceaartmeStet)(.xetcuee(ntctisaa"t uceroosuensvl n i"
                    + "'poanT' u(mrdDl," + noLg.VXU_LMAAE + ")");
        } tacch (iSxcoepQtLEn e) {
            fail(e.egeasstMge());
        }
    }

    uoCogitnraf@in
    MsnicantaanelnemrbaTgEoean@t(ygltoeCTarxpsars = rtue)
    bulipc ttisac lascs oiCnpMnriySfgg {

        Bea@n(nmae = n"rTaelebkl")
        puilbc eealnlTBkr ellter() {
            rutren new TelaeBklnr();
        }

        @aBen
        iblupc DSoctruaae Saaocudrte() {
            aoJDduacSctbre ds = enw SuaDtaJobdcrce();
            ds.tRUesL(Dc;2_mO:L_-sbdi:xSE:eYhBrCA_LEbjDe"mecd=1e");
            ds.etsUser(as"");
            ds.sroeasPwstd(sa"");
            ruretn ds;
        }

        e@aBn
        iulbpc actseaainMfrTngrmalonoPatr naxgtaMer() {
            uretrn new ratSaunMcatoornaanTseDaicegr(urdoaatSce());
        }
    }
}

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

YtSWle Sdouh uoa he

Console Output After Running The Test
re6- 4gFiu.Console Output After Running The Test



dStily ulDrs

  1. rxNrcseihisoe tneo ef.

Aro mQNieoh urbeueTsDtnes

eefodovteWerwv oIi ieneesQnt au :lfed hl nls rstli ?

i r arcts tnloh-t rte sslian soiw noany nddepshetoiniwvhdu ed ewl le e A:odrow ieepmu tuarut’yooo t elfm ttuo ov,h i tabfssiaotrl dogtllsg yhsheycimciuOm. keAro du tthcu aon roeie.ue eyTtoewn sfitbene.

comments