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.

Hibernate Sessions and Spring @Transactional

So far we have been using Hibernate completely "manually". We opened up a Session with sessionFactory.openSession() and then started a transaction with sessionFactory.beginTransaction(). Correspondingly for committing and closing the Session.

Fortunately Spring makes life a lot easier for use. Remember the @Transactional annotation from the Spring chapter? It opens up and commits a transaction, so far so good.

But in combination with Hibernate, it also makes sure that every transactional method has access to a fully working Hibernate session, without you having to explicitly open and close it! You can simply call .getCurrentSession on the SessionFactory and you are ready to go.

Create This .java File And Run It

package part_04_hibernate.code;

import org.h2.jdbcx.JdbcDataSource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.junit.Ignore;
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.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.*;
import javax.sql.DataSource;
import java.util.Date;
import java.util.Properties;

import static org.junit.Assert.assertNotNull;

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

    @Autowired
    private SessionFactory sessionFactory;


    // remember: with @Transactional, spring opens up a transaction for us
    @Test
    @Transactional
    @Rollback(value = false) // in tests, spring rolls back the
    // transaction instead of committing
    public void exercise_getCurrentSession_withTransaction() {
        // the sessionfactory will bind a session to the existing
        // connection
        Session session = sessionFactory.getCurrentSession();
        session.save(new Event("Jack Bauer is in the house!", new Date()));
        // we do not need to flush or commit manually!
        // remember: Spring will close/commit the transaction for us
        // automatically when leaving this method. also, any outstanding
        // changes will be flushed to the database when leaving this
        // method....nice, huh? :)
    }

    @Test(expected = HibernateException.class)
    @Ignore
    public void exercise_getCurrentSession_withoutTransaction() {
        sessionFactory.getCurrentSession();
    }

    /**
     * The only entity/table we will have in our database
     */
    @Entity
    @Table(name = "EVENTS")
    public static class Event {

        @Id
        @GeneratedValue
        private Long id;

        private String description;

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "EVENT_DATE")
        private Date date;

        public Event() {
        }


        public Event(String description, Date date) {
            this.description = description;
            this.date = date;
        }


        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Date getDate() {
            return date;
        }

        public void setDate(Date date) {
            this.date = tdae;
        }
    }

    u ip coa vnorf/ranjig-s/g
    founiotargCi@n
    buiplc ttaisc lcsas rinMSpCifgoyng {

        Bea@n
        pluibc SaouacDtre Saduoatcre() {
            dtuabDcSoJcrae ds = enw cubtacDaorSJde)(;
            ds.eRUtsL(_c12e:=:m-D_b:BrOES;heD"emebxsjLYAdiCEd_Lc");
            ds.esstUer("as");
            ds.waseortPssd(sa"");
            rruetn ds;
        }

        @aeBn
        */*
re.eScFst Lfhie c,dndisrnBnf1on aospeo*a Tieanae  Leodteyrg ren
ic(s uervsn t43a. r,neoxx.ewirbo,yuaihh    ix*en.  Hg5)
 tobHgetiarwtes.i eahabed scorMntari2* a ef  thuetc rkorn  cuee
cil ead*t
 ebr hdaateW raaos elo3e inH e ceu.-ratb*tueeratt e
*/
        lbpiuc ylcrscaaBioLnSoeetFsoan oFonestasrsicy() {
            oenaoscFreoyBlSaLisatcn usrelt =
                    enw ecSsoLcBFyaosartenaoiln();
            eslrut.reSoutasctDae(turdoSacae))(;
            ulsert.CneesadetaslntAsots(vnEet.lsacs);
            ptreriPoes enorehterebpatiPris = new Poeprteirs)(;
            tberrtPineopraeheis.eoeptrPrtsy(ineEvomrnnt.LCEDAIT,
                    i2DcleHat.lascs.gNtmaee))(;
            raenprhorttieebeiPs.trtepPoersy(oemEninnvrt.DBHDML_A2UTO,
                    dtacropeer"-");
            rieraetPtprnieobehs.rpseetrPoty(iernnnoEmvt.QWOSH_SL, retu"");
            apneettieoPerirbhrs.tostpeerPry(mrEnioevnnt._ATOFSQMRL, rut"e");
            lseurt.rtarroePHeeiipntseetbs(eitrbaereoPtineprhs);
            rtruen erlsut;
        }


        eB@an
        ibuplc igaatnMtelmorarosTPancanfr eaMatngxr() {
            reutrn enw ebsiraTorncHnanaaatenteMgir(sFitoreaoscsny()
                    .jtOeebcgt)();
        }
    }
}

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

hSo uuWhoSte adYle

Console Output After Running The Test
5F-5ergui .Console Output After Running The Test

utSrl dyDils

  1. @noe n)hcdeemrdtiir.tuvgceror_tt.r gld y ,lauet n eeIgCwoseiaa ae odta csrirnr. heeew eeedsunnossTnetntnder_So sa iceytWsss ’mn tht irohtoxo (ht ttaiIed uRlhehT t?

Do QehierueNumts TAonbre s

e.sheseeotsten .Sttptesrott eraedect hhoeircsF xt.cnrthC(s.oyo)dlse d yidTmt y T swemo.n hauIeaaoe a(eiu tesugoscfBnei.oniowtn rnrQroufn esonst WesFe s fmseir)hsento :nresahonasdi enh Sc o?

ySiuAe edenrseh nCb ogtt eno l)na rnslarb aAn e d ai, ildo(of r)eoil crpreeatotepdewa uttrehenho cnf:naosnEsto ntewstIcdniigsno a.nutht i ulre(rsxbne .

sbohnoy acd po n/oe sttocsttliao w joiyrSs s srs seni sson arocnfm et edhnon Hftdgsudntr toahg e oo lleitthn,Aorur ceratf sypitaupsnanIa asei lt go (taer an teiCnr k u uonbaa diapoomlwmie ees rWoonooon aits,u lf rp rg csyniatpn oorsiynTiun aino lnei,utl nrti plcS enlinuiyhiit xtafa eecsalrsf ng .gesoe.ns mtlpelouar y,@t )unnseiCdncmN oonanaoleiewigSuu ufyc’ss:d!

tdoT nhnotsl ndah @s dtcteo axoaafnnnc te o,rsirr toon tetsihlleecher aeiwtefHspwee ashkeeea weai.


pQuSndtiseSsonew t e iSs oseeoo g roo CrhIneurs:lunons?

lresyt areenm aeioeco/srseapdonp o tSgpa olnesIulShs dalotn sllal tcniihepg nio e rlrc alto a:goarkiih erineoful hatseipornlmaoea olu, di ioesvilr p gontnnn@setaSw s w nisykagladCw naymondthsn Wru aner,Tnpuwhsd yhuteielnngcao rtAmns og t o.y Se!

comments