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 JDBC Logging

We already covered JDBC driver level logging. Spring however also provides you with some logging capabilities, i.e. displaying when Spring opens up a transaction or commits it.

You can use your favourite logging framework and use it to set the logging level to DEBUG or TRACE on the following packages (following is a log4j example):

  • For JDBC logging: log4j.logger.org.springframework.jdbc=DEBUG

  • For Transaction logging: log4j.logger.org.springframework.transaction=DEBUG

  • For ORM(JPA, Hibernate) Logging: log4j.logger.org.springframework.orm=DEBUG

For this example I will simply modify the base logging level to DEBUG in my simplelogger.properties (see JDBC driver logging ) and execute a bit of JDBC code in Spring, which should result in some nice log messages.

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

    @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) {
           // 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(params);
            erturn naalcbe;
        }
        oohi evwmnhnt pn l/ o/saattece  n  rthdceclacisne gs ,eeoo dten
        /t / =x
    }


    tvirpae viod laTetraeecbs(eotcCinnon cnon) {
        rty {
            ocnn.aeeeStermtntact().xeeucte(t iiefet aexa blroe t stsn"c" +
                    u nats"cco"
                    + rmnyarga apveene myr( b"bta ,n laiari)cckih");
            cnon.nteeetStcmeaart)(.xceuete(ee"b xt sfleaai en rtist cto" +
                    yvaot_"ictaicnuc t"
                    + c(cupn"R ee atodHsroAeied_tAVd,,Rta icrrCd" +
                    aaar  m cvren",h" +
                    neenea)m n )sy)feku(reicagececm"oto rann( srfe");
            ocnn.amcaetenSrtetet().cuetexe(stn ointl nsvt"eecrcuuiaaos "
                    + 'dDprua("Tmnlo,' " + Long.UALV_XMAE + )"");
        } actch (EeScoixtpQLn e) {
            iafl(e.Magtssegee))(;
        }
    }

    uai@tiCfornogn
    Tt@eeailcnmgEsbnnnarenaaoaMt(tyaegsrCplxarTos = utre)
    luipbc itstac aclss opMnyifrgCinSg {

        @eaBn
        lbipuc kTanelBelr ltleer() {
            rretun enw nBaelTelkr)(;
        }

        aeB@n
        uilpbc SocDuartae tcoaarduSe() {
            uaaoJbrctDcSde ds = new dbarJauccoDSte();
            ds.UsetRL(cebeBcEDmsjCd1_2eLx-A"D:e:dEY_O_;S:irmLh=b");
            ds.eUtsser("as");
            ds.Ptsasoerwsd("as");
            teurrn ds;
        }

        @aBen
        public eatgtlancaMiansaTmnrofoPrr eaMgatxnr() {
            rterun enw onTerSrcaaogasncaetauitMnDar(uoScardate)();
        }
    }
}

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

hYh au Sdo eoSWtlue

Console Output After Running The Test
rgF-u14 0ie.Console Output After Running The Test



nv eo odx ,ieenn orc o L entmnaopfwo chcgerseneatuaádc tetbade ep ,neQ .sol,r iSceenwudeqsot ntea gA t u cuWo gaus yi t.

t DyluSlrdis

  1. gooot hge a krehtnoet/c noaptt og e yr tmlniofi 4k c2tsodsys uro,lat-u,yhe4tWlbrjogigs jemc fnn wmhsglakrwgpki.a je ncapar hrnel l sa f d etualiiiigeofTjinribrgeesr tnrlieasggo4nud

ur roiQeshbTDmene eA otuNs

wcnDQottkwrig ati olaig hro omeg e:tesesh u mrf ?

eh ocfrgereeetYero scgeio e fclooayeehn .v thianonmntlun te r e tvtono eh cAt mt toh da tuhs espogt oolkggtiheokhagmr, iot:loatrtireoghc tac rtni ptiif Neh naee gm np a ol s.

comments