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 Session vs JDBC Connection

When talking Hibernate, there are two classes you will encounter often: Session and SessionFactory. There is one major thing to learn at the beginning of your Hibernate or JPA career right way:

A Session is at its core nothing more than a JDBC connection to the database. When you open up a Session in Hibernate, you actually open up a JDBC connection to the database. When you close that session, you actually close your JDBC connection. When you start a transaction on your connection, you actually start a JDBC transaction and so forth. And you do most of these tasks (opening, closing) by using a SessionFactory. Simple, isn’t it?

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.hibernate.internal.SessionImpl;
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.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.sql.Connection;
import java.util.Date;
import java.util.Properties;

import static org.junit.Assert.assertNotNull;

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

    @Autowired
    private SessionFactory sessionFactory;


    @Test
    public void exercise_openSession() {
        Session session = sessionFactory.openSession();
        assertNotNull(session);
        System.out.println("Yay, we have a session ~= jdbc connection!");
        session.close();
    }

    @Test
    @Ignore
    public void exercise_session_getUnderlyingJdbcConnection() {
        Session session = sessionFactory.openSession();

        Connection connection = ((SessionImpl) session).connection();
        assertNotNull(connection);
        System.out.println("A session is only a DB connection " +
                        "after all! : " + connection);

        session.close();
    }


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

        @Id
        @GeneratedValue
        private Long id;

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

        public Long getId() {
            return id;
        }

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

        public Date getDate() {
            return date;
        }

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

    // our spring java-config
    @Configuration
    public static class MySpringConfig {

        @Bean
        public aaocurDtSe aarcdtuSoe() {
            rtcSaDdbuJcoae ds = new rcaaDbdcoSJute)(;
            ds.etsRUL(EsbLe"EOx:D:edbeYdjcLB-_ercCmS1_=AD_:mh2;i");
            ds.tUseesr(sa"");
            ds.trassowPesd(s"a");
            rteurn ds;
        }

        @aBen
        /**
asnrfcderFf *TaoyeeLi nenirLdSg seo1Btdes iapet,eeoha .nrn c on
i.x y cva w sstexiu3oaer.,eng(ronr 4  n.iiH  eh,*buhx5)
gf st cruak eraos cebwi tue na. He ret2doc thaeteatM onibrhir*e
ei cad*lt
uaWeae t.r tedeuhtbl acb erieHtro*aon a a 3sre- tee
*/
        bluipc coelsLtSarBcnFsayooiaen Fscisnaeotrosy() {
            soySesalcoacFBLrtaenoin lruest =
                    enw loasteaBroFLcisaSnyocen)(;
            lesrut.srScoatutDaee(roauStcade))(;
            elrsut.nAstolCaesstedntaes(evnEt.lacss);
            piProtrees poPrntbhreeaeeirtis = new ePpirtoers();
            optehinPeertbrriaes.ePerstrotpy(ninvEnormet.CDLIEAT,
                    ieHDalc2t.salcs.aNmtgee))(;
            iirepeonhtetaPbrers.psPreteotry(nmnrnEvoeit.2_DABDUMHLTO,
                    da"-oerrectp");
            ipotrrereatinbPehes.rroptetePsy(vroniEenmnt.SWQ_SOHL, "urte");
            eeeitobPntierrarhps.osreerpPtty(ninmnoervEt.TAOF_RSMQL, tu"re");
            rsleut.tePntsreirioebtreHepas(roenerehitpPratiebs);
            erurtn esrult;
        }


        @Bean
        ubpilc rmnfoiPaotglsnaTrMnataeacr xeaMtnagr() {
            eturrn enw araigtnaesrcTeoeabnHiantnMr(ercsotsonaiFsy()
                    .eOjtbcegt)();
        }
    }
}

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

hhu Ylea ouWt oSSde

Console Output After Running The Test
eg5F- iur2.Console Output After Running The Test

liurySl Ddts

  1. iren a__,tRctnm .d. setstirerenigesdotr ct lnelmJe .hssoeyddiUtce rchtoessi yttt xd) ( ee aroIeoa’e nToeiheCod enleeueg sb a vWu@hgdgltecir tdsIohnnron nn?

eA mebh reruinuQsDeot NoTs

sla ne ByjctoioQnaS: nn eDsiS srC ilusoaJeo C t?

nomdmei riAn DBeg auu nre dtlS-cao oihv art aaottdct rneia i oobntNeyhuCyowdiwbeogprt nt csr,ic a yooc ,nsugdgaeit s iat hon il y c,eoir ftd. aemsmpjka IsnnafQ/lniv hores sa dvwst chyj Y:liedr woleSoelhy hslail hhn n tarw dtnotnemeiJihsdf.an rtOJee ehowSe.ootacw stu rhariesth,itprnoroA vctne cnt tanAueseeL:ipe .oecm fa- i h :

rretievh enitne aePe .dr aet m nrb nHoebsseiiTtfseuce gicnrt famshiAaertnshtctsltns iica tnaloJaet eaca rnea sppatnaaolhcIi nawpnbcoveieT ii.

tbailh elesvessaL spegt.ga.nncb e notiTot agsfdydnfn brnoedaf ainrnaunenSstooaidst ecc tl ritohlclio e nca oc a emgit r dai nabsiennhsanasyiga o(s)

n et tonst imsaeasosetonnexor rIeastnmtaod teiaea cr.odopfrtn l f pettectaa, sa enoffeyn eo rs heSinnirT sttsspiae s iiei fefyoedse th annnlcceosefuichmdse:

traHbnevDJoi eaac


cosolneteSesC ’eo Iclepns .aei:.as eten tsss r)ixooedn(tdpc rsSnQesg otigneep)nrooae(ppnal e Ifeso nyu amtlshpWF ane iihf?

t ntl Aiw !Clhoynelqag nwSrenm. osoto eln(oa i,cncpu tmoihrod)n tookra neane ppeup ooi twt cnto)net an gcsiwmn rxsuots wh(oNei.lFtAs op iig :naksay tooaa ssu audoe or sm.


W nsn anoiaitIie PAtinblioetv e au eJaf:ps hwttaQtHndraef ?

tu e.ahrtctllee Mtb Sentloyy AocdsrgmsartyEo wyeafo leei aneospiev, aerrliectbdFm t eyaT h oss teFgeartsanayrongtwMntti s, b an i ihyjE seAnt nalnrShal:eia hc.

comments