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 Stateless Sessions

In the previous chapter we looked at plain Hibernate Sessions (~JPA EntityManagers). As we learned, a Session provides some more functionality on top of a plain JDBC connection which can be costly in some circumstances (batch jobs, updating thousands of records).

For those cases, Hibernate provides you with a StatelessConnection, which is almost literally your JDBC connection, without any extra features.

Create This .java File And Run It

package part_04_hibernate.code;

import org.h2.jdbcx.JdbcDataSource;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.internal.StatelessSessionImpl;
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 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 = StatelessSessionExercise.MySpringConfig.class)
@SuppressWarnings("Duplicates") // for IntelliJ idea only
public class StatelessSessionExercise {

    @Autowired
    private SessionFactory sessionFactory;


    @Test
    public void exercise_openStatelessSession() {
        StatelessSession session = sessionFactory.openStatelessSession();
        assertNotNull(session);
        System.out.println("Yay, we have a stateless session!");
        session.close();
    }

    @Test
    @Ignore
    public void exercise_statelessSession_underlyingJDBCConnection() {
        StatelessSession session = sessionFactory.openStatelessSession();

        Connection connection = ((StatelessSessionImpl) 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 DataSource audtrocSae() {
            ubDccSaoratdJe ds = new SabDrcucdJoate();
            ds.tReUsL(":hm_mieeeeD;rdccb:SBx2-jsE:YbLdCLAO_DE_=1");
            ds.esUestr("sa");
            ds.stssawrPoed("as");
            rruten ds;
        }

        aB@en
        /**
iec soenneyoia eraLn,o ctfBFongd1dn p e  hderrsaeL*f.TsSietraen
  exi3 ot.y eH.5nn i sun4eaurxix r,gaeh ,b*(w hirsc.vo)
 cu.bus  toagci *rsfh c  ewat ienttoreedi2h HbraMeek raatternoe
 adelc*it
euaaosrrbeoc utea.l  *ateW e  e thnear3idbt arHet-e
*/
        uilbpc nLFrscaBlyooceatSosaien easonriocsFtsy() {
            icasBooScerLonesalayFtn uslret =
                    new cSooarssLBaaoetFleyncin)(;
            eulsrt.DtrSetscauoae(dtoacuSrae());
            result.CeneslnststdaeaotAs(Envet.csals);
            ieoPprrets brPrtetenioeirpaehs = new etoPrierps)(;
            tintroereePprehbias.teepostrPry(nnroEiemnvt.ALCDEIT,
                    2DecilHat.lcsas.emNatge)();
            eehrioinPebetarptrs.oPptsrterey(oimEevnnrnt.2AH_TBDULDMO,
                    reedptro"-ca");
            riorenheeapeiPtbrts.toePertprsy(inmnrneEvot.S_SWOHQL, rtu"e");
            rpetibetorenareihPs.Peotetsprry(nrenoEvinmt.OTRAMSFQ_L, tur"e");
            uslret.nbtsrHreeoptPeeiireats(Peotapirrtirebhnees);
            trreun uerslt;
        }


        B@ean
        bupilc crftnaMtanPTmlaagooaerisnr natMxeagr() {
            ertrun new irMoTgneatsiaeanareabnHntcr(siaosoertncFsy()
                    .tOeebjgct)();
        }
    }
}

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

YoSul ShatuW odh ee

Console Output After Running The Test
u-5 rgeiF3.Console Output After Running The Test

Dry dtluliSs

  1. .ttoretesn eecrsed sh olCTstl yWe(teintssny Cnoatt ui@vgeeatto Iiaeiehrxt’trlaBicsoh_ ,eimdolter teoJDleer S n .mr e.e rhId ggndcsdnss_u)nee iaheoenus dncRond?

roou TteDuQ Asn Nbreme hies

tot, aoeSesse ilcotta t hln caswnydetho eseex osdhanSSsreo t omsoedit QpS: ?

teubaHian mfecT ho mAge nnitaedei:ilot crooo ti rrtn:

i’r -eoltwaet eoeae- ct eiirltb cbalsynHvesln ovnatsekb reapn asccdmk soalfinlnnlwy t sidotene a out- itotcaeeellc bnetoia elo,bista o ti s nnndvtitnccsssr sdauh y l, rnmm vpansClias e thseatete l aade arnosmro pe ooecntelctn tigrrfssaessha sapeieirnhpde sr dov ntiocorepooeas,eseiiaopss fteesairesacl.ttdirncens ms-t os. tnn sooesrOfeslarer dcesne s oiea ie a cASirlosa ttedmintars ottscdlgeivgiadttcat imt a i dra eeunc eoeysnhceaheee tehnefafs ri.csaolstlesod.

nh mf,dFiesiesllfeaapottn ss sa ea raofcoo sirhnserst ret y ks toams no aiftuesrslsnrianlgstya ctitnteas.

nibarJ vHeoDteaac


sIsoe Ssei hSSalsideuo tnn asQtlyra wsseS sl:osu ose?

oawfn,r neyi hs otr tao soadyh stsh eetoowntlyyi c ts.i/Inin rwff Sehunl eaatoS s giSc haau idovenu eo eeh usi puge bt tltstfnn,dnAgIsobet:airhoroajeesusset uis.

comments