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.

Opening transactions and committing across two DataSources

In the previous chapter we set everything up for our distributed transaction (also called two-phase commit). Now it is time to see that two-phase commit in action.

Assume we are working for a bank, which has two databases for whatever legacy reason. When we register a user, we save his name into one database and his ATM withdrawal limit into another database.

This example might seem a bit far fetched and in real-life you would likely have a database and a JMS datasource, instead of two different databases. But apart from the set-up, everything else stays the same. So let’s have a look at the code:

Create This .java File And Run It

package part_05_xa.code;

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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;

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

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

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

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

    @Autowired
    private PlatformTransactionManager txManager;


    @Test
    public void committing_across_two_datasources() throws SQLException {
        // look back at the spring chapter if you do not know what we
        // are doing here. you can also use TransactionTemplates
        System.out.println("Let's open up a distributed TS!");
        TransactionStatus transaction = txManager.getTransaction(null);

        final String name = "Shannon Briggs";
        final Integer limit = 1234567;

        // let's commit the user in one database....and yes, that create
        // table statement should not be here, but is for simplicity ; )
        new JdbcTemplate(ds1).execute(
                "create table if not exists users " +
                        "(id bigint auto_increment primary key," +
                        aa rmecn) vr"ha");
        enw leidnsmcpISebrJt(sd1).itamTlbheawNe(ssru"e").etucexe(
                enw lrPtarapScueqmrMaoSee("anme", amne));

        tia s/ u'etus rvwtw elosie mdtn ea swha' rwaatssem/a h stl
        a.l t/tsoaanst.a oreimdtbih e /.
        yshsna,oe/ie(to  psrefr entl i h oog  nirider/an
        itnxepam  ih/ e/ ;lke  ys)
        enw bmlTeacJdtpe(sd2).eucxtee(
                selttmtd c_l  aeeestrowrfdt "hi atamiiibatni_awx ls" +
                        ri(nemnucgdpem ainbttyi iork_e y, tr "ia" +
                        mao t)i"tnnu ");
        enw meirdlpecbnIJsSt(sd2).aihewaNTtlbme(smwimlwada_dtath"liir_t")
                .tceuxee(enw apeqmoaalrcutSerPrSMe(tmona"u", liimt));

        agnaeMtxr.moicmt(atrcntiaosn);

        tyesSm.uot.riptlnn(omuttio ytc X i afmsis-srYAr"i h,");
    }
}

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

Wo laodYthuu S hSee

Console Output After Running The Test
2e7-Fguir.Console Output After Running The Test


aot ue rosiibreugfs tcd setawlsetweoiustta rurd s .o aetto utorlmh,iu slstf isdwly s hetg uhaealosade re tuearDvntmiltehcnadmmhe dodensssralgttnfioty aiceotnsuutt aScsic ecafrihe w ee onl wlkbhcaarfewda. O n m eewi ennnbhaigau yirweon caa rssot agTWsT ontc:se isMudnreaulyija eoba y hfcs ireauant tyt rao sctd seaetdmwPn ap dogosurinP elote truncl ee sela.

dD lutSilyrs

  1. ea/etJA ssttdwud iak.oeawe/ptm:SecsW rotoaur miealeitvtehnr Ysoeatniedtuis.oem t nsd/pate be nM:bdp re iiacd/odtQgMmntatsdap u edue-.hpfo l ob o.tootcc hhkpathpuhcgawuh s ,ri.tNree It.sart - lbef l oeo qv l

  2. t. aasasown sd oe hat soosgrcCpeaud ettryanidsgrmaeirhrcy h W uEip Mupt o m nrnftihrat nuh n t tcldhfcarloCsenaot? aRaituaeungio tn uical lnhtdntt socehraaeOdeacsa m?

rAmuN ebe oi esouheDQr tnsT`

iu:m iu o n n om… utQohsrsn.eIUfqtagn.

atuCguteklhricsodhettaIsnienAmTuh.tothe o dc qesrieryhsi e s icoti nenp:teofd aas srei wcrepitdut b rs bmboeat hsae vuait:n)

comments