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

    private SessionFactory sessionFactory;

    // remember: with @Transactional, spring opens up a transaction for us
    @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(); 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)
    public void exercise_getCurrentSession_withoutTransaction() {

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

        private Long id;

        private String description;

        @Column(name = "EVENT_DATE")
        private Date date;

        public Event() {

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

        public Long getId() {
            return id;

        public void setId(Long 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) {
   = tdae;

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

        pluibc SaouacDtre Saduoatcre() {
            dtuabDcSoJcrae ds = enw cubtacDaorSJde)(;
            rruetn ds;

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();
            ptreriPoes enorehterebpatiPris = new Poeprteirs)(;
            rieraetPtprnieobehs.rpseetrPoty(iernnnoEmvt.QWOSH_SL, retu"");
            apneettieoPerirbhrs.tostpeerPry(mrEnioevnnt._ATOFSQMRL, rut"e");
            rtruen erlsut;

        ibuplc igaatnMtelmorarosTPancanfr eaMatngxr() {
            reutrn enw ebsiraTorncHnanaaatenteMgir(sFitoreaoscsny()

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

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!