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

    @Autowired
    private SessionFactory sessionFactory;


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

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

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

        // and commit it
        session.getTransaction().commit();

        // close the session == our jdbc 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;

        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 = date;
        }
    }

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

        @eaBn
        uiplbc utaocDSrae artSocaude() {
            doDurtJbccSaae ds = enw baurSodaDcctJe)(;
            ds.UteRsL(_jbh_mrx-ec:eE_ciOL"DSAmLDEdCBe:ebs:;12d=Y");
            ds.tessUer(a"s");
            ds.roestPawssd("sa");
            ruertn ds;
        }

        Bae@n
        */*
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
 aec*dilt
3eea bdtt thbtutl*i-rc.ae eoaea aareernes ou r HW e
*/
        public esoLFsaalSoaecoycnrtBin tesFoaicrsnsoy() {
            FrlencootBacsysaSLiaoen lusret =
                    new cnSaseFritayoLBsooeacln)(;
            esrlut.SseatcDtrauoe(trdacuaSoe)();
            uelrst.teAtdeCasoesltnnsas(Enevt.acsls);
            retPreipos orarethPnepieetribs = new rrePitopes();
            Pneoarepierhrttebis.etpsProtery(emEonnrinvt.ILECDAT,
                    iaeHD2clt.scals.teNmgae());
            aebrtpieterrenhoiPs.sPrtorteepy(nonmievErnt.DM2_ADHULBTO,
                    cdoe"r-eatpr");
            etrpernoiebPtraheis.ereoptPstry(rennomivEnt.WSQHSO_L, "tuer");
            ibtereperthaoPierns.setpeotPrry(enrnivnomEt.SAFMRTOQ_L, te"ur");
            esrlut.ttsiereeenHetiPprrbaos(Preptitaenrirbeheos);
            turren rluest;
        }


        @Bean
        buplic TtfotlPnacsiarnaaneMgrmoar aMagxetnr() {
            tuerrn enw oncaiHennireMteTbnaaaagrstr(crssnoiatFoesy()
                    .ejbgtcOet))(;
        }
    }
}

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

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.

comments