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 Transactions vs JDBC Transactions

Quite a while ago we learned how to open up transactions with plain JDBC ( Starting And Committing A Transaction ). This time we are using Hibernate instead, which does exactly the same things we did before with JDBC, internally.

Create This .java File And Run It

package part_04_hibernate.code;

import org.h2.jdbcx.JdbcDataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
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 javax.persistence.*;
import javax.sql.DataSource;
import java.util.Date;
import java.util.Properties;

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

    private SessionFactory sessionFactory;

    public void exercise_openAndCommitTransaction() {
        // get a session == jdbc connection
        Session session = sessionFactory.openSession();

        // lets open up a transaction. remember setAutocommit(false)!

        // save == insert our objects Event("Jack Bauer is in the house!", new Date())); Event("As is Habib Marwan", new Date()));

        // and commit it

        // close the session == our jdbc connection

     * 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) {
   = date;

    // our spring java-config
    public static alcss pMninCSrifoygg {

        uiplbc utaocDSrae artSocaude() {
            doDurtJbccSaae ds = enw baurSodaDcctJe)(;
            ruertn ds;

a ee*Soe yrn s,dedpaoLBsaoig.anerf en Loir 1nhstfdniFcTecr eten
rheix .nst ,orhac.Hiie3wugxv * sirya 45 bu,n(nee.  o x)
 u g.cirs n2tubee at ewrh*ettareabceatMohi  ntfdacirsH koeo  re
3eea bdtt thbtutl* eoaea aareernes ou r HW e
        public esoLFsaalSoaecoycnrtBin tesFoaicrsnsoy() {
            FrlencootBacsysaSLiaoen lusret =
                    new cnSaseFritayoLBsooeacln)(;
            retPreipos orarethPnepieetribs = new rrePitopes();
            etrpernoiebPtraheis.ereoptPstry(rennomivEnt.WSQHSO_L, "tuer");
            ibtereperthaoPierns.setpeotPrry(enrnivnomEt.SAFMRTOQ_L, te"ur");
            turren rluest;

        buplic TtfotlPnacsiarnaaneMgrmoar aMagxetnr() {
            tuerrn enw oncaiHennireMteTbnaaaagrstr(crssnoiatFoesy()

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

hoWdo hSelStau Yue

.Console Output After Running The Test
iF-rug45e .Console Output After Running The Test

i dyDrtSulls

  1. lrsaeomhtstiene aaoa agifccydtb lcgd tth mkb at gsoIt thinnnmte,e roeh.

  2. a ht estialjlshan bR aonT?avihatycrdeionnatab r eptch aewtvdJ eoo ohareth ttleoWacD mhe eam

Ne otATQm sre ubnhoe ueriDs

hy anvlt nnehmoQoccuf toI aatnod taampsetlrtl i ei:ires lnlim nauakia pDe o?

a hetgirts ari fbnienp ’rIc iannala eylgdnwcps ue ncsthomeateerxuaenmh,ubeoavn iurprh.of A rH, o ort epHIto o o:iyi um ngaStwe e nioekispcyan@ t i hriifsb oSneie t b ghroi riwau ,cahlc oTapnr n eyfc lgtwoa n.