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.

Setting up Hibernate with Spring

When it comes to Hibernate and Spring, the setup is actually rather straightforward. The only thing you have to decide up-front, is which Hibernate version to use: 3.x, 4.x, 5.x. Depending on the version, you need slightly different Spring setup helper classes.

Our goal is to get a working SessionFactory (~EntityManager, for the ones who prefer plain JPA) for Hibernate 5. For that we create a LocalSessionFactoryBean, which is a helper class provided by Spring which actually creates the SessionFactory for us. In addition, we are going to be using a HibernateTransactionManager from now on, instead of our plain, old DataSourceTransactionManager.

pom.xml

Add these changes to the <dependencies> section of your pom.xml to be able to execute every test file from this chapter.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.0.1.Final</version>
</dependency>

Create This .java File And Run It

package part_04_hibernate.code;

import org.h2.jdbcx.JdbcDataSource;
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;

import static org.junit.Assert.assertNotNull;

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

    @Autowired
    private SessionFactory sessionFactory;


    @Test
    public void exercise_setupSessionFactory() {
        assertNotNull(sessionFactory);
        System.out.println("We have a SessionFactory, yay!");
    }


    /**
     * The only entity/table we will have in our database
     */
    @Entity
    @Table(name = "EVENTS")
    public 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 DataSource dataSource() {
            JdbcDataSource ds = new JdbcDataSource();
            ds.URestL(A:beBd_dO-hi1:mED;Drm"E_Ljs2e:CcSxcY_=Lebe");
            ds.eetsUsr(a"s");
            ds.sPoatsesrwd("sa");
            tuerrn ds;
        }

        ea@Bn
        /**
aanLeaor opfs*aoeS endogcFy,sihr  ner  Le1edniscrtnefBd Tte.ien
w,hirivyauixsr*..e h  , etex3 nos4b c 5x Hu(aning .ore)
r oe2e frr i na.se o uh hosr*aeki ten tebtarwccbHtitgaca Meudte
acei*l dt
nu  a3.h ab e-*eare uoHecett rtaeresaorteWa dti lbe
*/
        uilbpc eSlcFiscBotseornayLaoan Fscaesotrnsoiy() {
            oicsrlotaeLnFyeaoSsBcan rlesut =
                    enw cLonlersiceFBotySsoaaan)(;

            stdrs/t ua  rcae/ooue
            esrlut.asrttucDaeSoe(uaodcrStae());

            ab/swpe ln thango /im ah twepntiteeolakrn   w
            sluret.snlAteCeadnatstesos(Eevnt.cslas);

             pstorru/b ceeieft aa/tasia,dapooi el  ncod:cter-ttae.
            reerpiotPs aiirrntehPerpeetobs = new rptirPeeos();
            Peoateinpheeritbrrs.etrrPopesty(rEovmnenint.ACIELDT,
                    cHi2aelDt.lcsas.atgNmee))(;
            /*
peDrnorrAs.tEsytiobHL_PateTi(iBnnmpU.theoterOerrveMDePn2,
pra-deor)t""ce;
*/

            /*
rSnttSWi(pr)er.reyerLor"OP,ntim"repeoseuQsHEtaoeeti_bht.Pnvn;
i"ee_r.sFrreRO.nab"tooPrttAtnSvoEeteymrLeer)(rspunQP,MehtpiinT;
*/

            eurslt.eieaseerHPeropbttntirs(beanihiteorPrpteers);

            uerrtn selrut;
        }


        Bae@n
        bpiulc PsTiaaftlaoamrcaMonrngetnr tMnaagexr() {
            treurn new nanonaertgiTbHtasneacaeiMrr(seotrcsioasFny()
                    .gOtbeject)();
        }
    }
}

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

uS oW hahodYtulSee

Console Output After Running The Test
iF-5re1ug .Console Output After Running The Test

rl iSyldtDus

  1. gld.i,nanrrdeeooi o hee a e1onoy B0t sSraptrsgIob5a omiaeveh Ler fpnntlcn ftot ,a n h d m.ftccnn:onuHric yeyreurec34ttbveitte/i ufgHbTaismat rdeaFs n yntntvoytrlibmsnenn r dor cadienkney .soAsa. Mte eveaaer.osses ioerFieurcnaHntrvep t// oetyprooeMaaaeefsriLhs.

  2. orehyRd ueSen xnma eoHsmner cptQ i muai otn.g oges elesvs hometgaottin rtilm nn c eabestn dct.o- Llretn.buepeIhtusllcne aaceriei Wtrhf anee r?

  3. a tre ot aoe cie_fa.e2aLoiusmaarb Ac rlei anehest n ctr imnmeylMeettdtenDr si.oWn e uibrttlnt netueanemv-dmcta on isocthe neEaaYasceraensmTexuhecnBtUHd.mp msn h et petertdfRnohufiD .aoalotOiblHov?

AoTorueNQ neie uetmshD brs

n uhHsaowh:ode eteivarteu ybir seantllaSe s ltQIs?

tt:l yaoptj0e ut runr nl nu4otrA aa e oo ddsifeioufdtkaorhopttba enecenp 4sei ibb5.gin ann dm +u li wrease nrwe ggliestsipeyow5sH,Hhaeuytgen t wtr1astu 5l A so tes eeetsHHalte S.oif nit.oaewrurrtbt3ut liselpo so sa2 ,r2ns v ri ruhaBerraA.


rffs:ataaoge Wt dPaenmfoniedeQd niaheMnayrT rw con retl?

uguog na sRi eantswoetar et e?mtcIjair./taal aory abrl sstptoesia a:sooAsaaedaPiru et hnuafaebtow hsw/tirnanma nwseo n oeoi gumnclinil lend s tliio it-botrt/l /cnrnrtcccd ymhnsnlaTp deay algtse ttes atrinm rcyofcrrrirn i sag a ccsopSHroa em enntmstrhaDaaoitsminonetfnftoecMgao seeinelncnm.

tr shBetftetnauo cen)n tBmol i ntdn oo aoe ewnh clksoatlttltai neJclo dis0e EonetTt a elowid s0oa h wath asinns a!(t sii conooim.m a;eru )nClnonunr a(ap eJ t s~agoHnt ttiAbhotaolorlrc mt mn tracru h thahlvytseth?teCrheDe tADrhlsabeeasapdjy Bhe w taet5e ceneiaru edp)

comments