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.

Distributed Transactions - Bitronix, PoolingDataSources and JTATransaction Managers

What if you want to commit simultaneously across two or more datasources (it could be two databases, it could be a database and a JMS message queue, etc) ?

The simple answer is: You need a transaction manager which is capable of committing across these datasources, a so called JTA transaction manager. If you are not running an application server but just plain Spring as we do, you have a couple of open source/commercial JTA implementations to choose from. We are using Bitronix in this example.

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.codehaus.btm</groupId>
    <artifactId>btm</artifactId>
    <version>2.1.4</version>
    <scope>provided</scope>
</dependency>

Create This .java File And Run It

package part_05_xa.code;

import bitronix.tm.BitronixTransactionManager;
import bitronix.tm.TransactionManagerServices;
import bitronix.tm.resource.jdbc.PoolingDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

import static org.junit.Assert.assertNotNull;

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

    @Autowired
    @Qualifier(value = "dataSourceOne")
    private DataSource ds1;

    @Autowired
    @Qualifier(value = "dataSourceTwo")
    private DataSource ds2;

    @Autowired
    private PlatformTransactionManager txManager;


    @Test
    public void setupTwoDataSources_and_txManager() throws SQLException {
        assertNotNull(ds1);
        assertNotNull(ds2);
        assertNotNull(txManager);
        System.out.println("Yay, everything is set-up for distributed " +
                "transactions!");
    }

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

        @Bean(destroyMethod = "close", name = "dataSourceOne",
                initMethod = "init")
        public DataSource dataSourceOne() {
            PoolingDataSource ds = new PoolingDataSource();
            ds.setClassName("org.h2.jdbcx.JdbcDataSource");
            ds.setUniqueName("ds1");
            ds.setMaxPoolSize(10);
            Properties props = new Properties();
            props.put("url", "jdbc:h2:mem:ds1");
            props.put("user", "sa");
            props.put("password", "");
            ds.setDriverProperties(props);
            return ds;
        }

        @Bean(tosytreedohMd = cosel"", anme = atruoeS"Twadoc",
                ttihienoMd = nt"ii")
        upiblc aauSortcDe woaraudceTtSo() {
            oloDaaniguSoPctre ds = enw tuDnlooPaaoicrSge();
            ds.esaNsmstlCae(.eDubSacbxcj.o.dhtcoa"rdJgr2");
            ds.UnmiqstNeauee(s"d2");
            ds.eMPsStixaozloe(10);
            prPteoeirs ropps = new protrPiees();
            ppros.upt(u"lr", 2:m:eddch":b2smj");
            oprps.put(urs"e", as"");
            props.upt("wpaorsds", "");
            ds.reeietsetDvrriropPs(ppors);
            erutrn ds;
        }


        ea/g /gtia ran rseogacns   upninaslTair'tlMarsJsoar
        Mr tPaanirgnotn/a/lafacoesmTr
        @aBen
        bpluic ianlonMgaamtaesoatnPrrfTcr aiaajntegtsnaTacnroMr() {
            ruertn new oraaMgtTanesnJiaatncr
                    (iiaexbanogMtrnr)(, ioetanMranixbgr))(;
        }

        Bea@n(yMosrhedtetod = wutnsho"d")
        pbluic tBraiaMnxonoTrnsgnatcaeiir xaMrtaoibginner() {
            rterun norMeeTtrecsgaiSanrniaacvs.igTrMnngteoanacaatser)(;
        }
    }
}

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

SuhootdS WahY ule e

Console Output After Running The Test
u-1Fei7gr.Console Output After Running The Test


A,dtra niiaoraho ieessuadhbt weo sccseyhs o B icTu xsfcwltt isnltanor otitsobc adwni l ewtgr ssahtnoulu iotienruaaPeioeeae.hcreadsaitead lsnhis d s c litroDltnsmatrselpaatSr a h dfhwu wnuev opr ,iacme.

rdithhnrA lcnoltes odacesrdee,s aAhoh oewhaet slttte uap o rri iwr egndctecbaeJmuTMi e webrttxma nh.epnctusu nss e aenie inpnhottr rtuta hernitraant hc Iicos ttonw diaw le .

l dDitruySls

  1. nTn e ( oaay u?artiruno)Cloth t ncCu lcntlDe Ssat oseoctouigy uasea .

  2. rcgTcie/ n nu aosfyiotasn / o aawMcbrriveTsanrgr aa )lanofmwoaagrstbc/el Bi/Tttgcriinulseopxbniaiue/setotrgoimi(aarfdrg.tnrafttcuxca xa gntk ondaotngha. nkGeohlosoeoinecniaastu nctv nemoutntrte-ghihiiaebi.Ms hnslaarrte.c niiab i/: EhS-inutnis te gdou opgnoof!

  3. soA edSttowtn.deGtd dco elico eet swtlenh hewynbum oaaiDtrgh uuem u/.eah oawaiB atnatroarftnkto / c oitsaJcuemut nid wuivo tts:eiox2t a octo o t trroe i iilero uunwlal.eis aDtp oao.T rGla d agms/tattgsid snyuesnnioStpn rsteuiSeY alhe npplktMew wflncgadaat,favg/.

e hmAieeobnsQo trr euNTuDs

ra : JsTa srnitArctogQa hrhhWcr tmen tianaeeohee?

ortah:a eoiB ixriis trttnoAn:an wkmhN ,aoGy sf e ,yhteeoAa


own l ottos twiIntssSoas’QtsmDia:ce cugcmoar r?

ray.cema ucm mtut a edepfotvioseerr tulrpr htaoiTgouvnedent irg.apcaalniir/siindxesn uho opptb lcS /smpihietcrroBtteuYaae id mtgucnnseoemh /n ss ttq: t.ce esm totem tscadhvu omAhmtmr tr.oppl tesfn ecytruean fnxehae-l-iitwihmtdh deqoaaeosulos yma e sd /deeonmiBaoul duxsr.uhf:oo arr tmt en -iusoso n eminH er:uaass lsdensoy,eo eo irbhsru toiydacj p p. ire.

comments