Example usage for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition

List of usage examples for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition

Introduction

In this page you can find the example usage for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition.

Prototype

public DefaultTransactionDefinition() 

Source Link

Document

Create a new DefaultTransactionDefinition, with default settings.

Usage

From source file:es.upm.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * /*from   w  w  w  . j  ava  2  s  .  c o m*/
 * Check that not existing control are created.
 */
@Transactional(propagation = Propagation.SUPPORTS)
public void creationControls() {
    try {
        DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
        // Set user for testing
        tx.setTxEndUserId("userForCreation");

        List<DbeExpendControl> controls = controlService.getExpendDataForUserAppProvCurrency(
                tx.getTxEndUserId(), tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertTrue(controls.isEmpty());

        // Update limits.
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        limitService.proccesLimit(tx);
        transactionManager.commit(status);

        controls = controlService.getExpendDataForUserAppProvCurrency(tx.getTxEndUserId(),
                tx.getAppProvider().getId().getAggregator().getTxEmail(),
                tx.getAppProvider().getId().getTxAppProviderId(), tx.getBmCurrency());

        Assert.assertNotNull(controls);
        Assert.assertTrue(controls.size() == 3);

        // All the new control have to be set to 0
        for (DbeExpendControl control : controls) {
            Assert.assertTrue(control.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0);
        }
        ProcessingLimitServiceTest.logger.debug("Controls:" + controls.size());
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());

    }
}

From source file:com.krawler.spring.organizationChart.organizationChartController.java

public ModelAndView deleteNode(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {//from ww  w . j a  va 2  s . c o  m

        boolean success = false;
        String nodeid = request.getParameter("nodeId");

        if (!StringUtil.isNullOrEmpty(nodeid)) {
            HashMap<String, Object> deleteJobj = organizationService.deleteNode(nodeid);

            success = Boolean.parseBoolean(deleteJobj.get("success").toString());

            List<Empprofile> ll = (List<Empprofile>) deleteJobj.get("childList");
            Empprofile emp = null;

            if (deleteJobj.get("deletedEmployee") != null) {
                emp = (Empprofile) deleteJobj.get("deletedEmployee");
            }

            User parentEmp = null;

            if (deleteJobj.get("parentEmployee") != null) {
                parentEmp = (User) deleteJobj.get("parentEmployee");
            }

            if (parentEmp != null && emp != null) {

                if (emp != null) {

                    String details = emp.getUserLogin().getUserName() + " [ "
                            + emp.getUserLogin().getUser().getFirstName() + " "
                            + emp.getUserLogin().getUser().getLastName() + " ] Un-assigned from "
                            + parentEmp.getFirstName() + " " + parentEmp.getLastName()
                            + " , and removed from Organization.";
                    auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_DELETED, details,
                            request, "0");
                }

                for (Empprofile e : ll) {
                    String details = e.getUserLogin().getUser().getFirstName() + " "
                            + e.getUserLogin().getUser().getLastName() + "  re-assigned to "
                            + parentEmp.getFirstName() + " " + parentEmp.getLastName() + "  ";

                    auditTrailDAOObj.insertAuditLog(AuditAction.ORGANIZATION_CHART_NODE_ASSIGNED, details,
                            request, "0");
                }
            }

        }

        jobj.put("data", "{success:" + success + "}");

        jobj1.put("valid", true);
        jobj1.put("data", jobj);
        jobj1.put("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn("General exception in deleteNode()", e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj1.toString());
}

From source file:org.mybatis.spring.MyBatisSpringTest.java

@Test
public void testWithJtaTxManager() {
    JtaTransactionManager jtaManager = new JtaTransactionManager(new MockUserTransaction());

    DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
    txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED");

    TransactionStatus status = jtaManager.getTransaction(txDef);

    session = SqlSessionUtils.getSqlSession(sqlSessionFactory);
    session.getMapper(TestMapper.class).findTest();
    SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

    jtaManager.commit(status);//  w w  w. j  a va 2  s.c  o  m

    // assume a real JTA tx would enlist and commit the JDBC connection
    assertNoCommitJdbc();
    assertCommitSession();
    assertSingleConnection();
}

From source file:com.krawler.spring.crm.common.documentController.java

public ModelAndView addDocuments(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    List fileItems = null;//from  w ww. ja  v a 2 s  .c o  m
    String details = "";
    KwlReturnObject kmsg = null;
    String auditAction = "";
    String id = java.util.UUID.randomUUID().toString();
    // PrintWriter out = null;
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
        response.setContentType("text/html;charset=UTF-8");
        // out = response.getWriter();
        String userid = sessionHandlerImpl.getUserid(request);
        String companyID = sessionHandlerImpl.getCompanyid(request);
        String map = request.getParameter("mapid");
        HashMap<String, String> arrParam = new HashMap<String, String>();
        boolean fileUpload = false;
        ArrayList<FileItem> fi = new ArrayList<FileItem>();
        if (request.getParameter("fileAdd") != null) {
            DiskFileUpload fu = new DiskFileUpload();
            fileItems = fu.parseRequest(request);
            crmDocumentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
        }
        String docID = "";
        for (int cnt = 0; cnt < fi.size(); cnt++) {
            kmsg = crmDocumentDAOObj.uploadFile(fi.get(cnt), userid, companyID, getServletContext());
            Docs doc = (Docs) kmsg.getEntityList().get(0);
            docID = doc.getDocid();
            String refid = arrParam.get("refid");
            jobj.put("userid", userid);
            jobj.put("docid", docID);
            jobj.put("companyid", companyID);
            jobj.put("id", id);
            jobj.put("map", map);
            jobj.put("refid", refid);
            crmDocumentDAOObj.saveDocumentMapping(jobj);
            String randomid = java.util.UUID.randomUUID().toString();
            crmDocumentDAOObj.insertDocumentOwnerEntry(randomid, userid, docID);
            if (map.equals("0")) {
                CrmCampaign c = (CrmCampaign) hibernateTemplate.get(CrmCampaign.class, refid);
                details = " Campaign - ";
                details += StringUtil.isNullOrEmpty(c.getCampaignname()) ? "" : c.getCampaignname();
                auditAction = AuditAction.CAMPAIGN_DOC_UPLOAD;
            } else if (map.equals("1")) {
                CrmLead l = (CrmLead) hibernateTemplate.get(CrmLead.class, refid);
                details = " Lead - ";
                details += StringUtil.isNullOrEmpty(l.getFirstname()) ? "" : l.getFirstname() + " ";
                details += StringUtil.isNullOrEmpty(l.getLastname()) ? "" : l.getLastname();
                auditAction = AuditAction.LEAD_DOC_UPLOAD;
            } else if (map.equals("2")) {
                CrmContact c = (CrmContact) hibernateTemplate.get(CrmContact.class, refid);
                details = " Contact - ";
                details += StringUtil.isNullOrEmpty(c.getFirstname()) ? "" : c.getFirstname() + " ";
                details += StringUtil.isNullOrEmpty(c.getLastname()) ? "" : c.getLastname();
                auditAction = AuditAction.CONTACT_DOC_UPLOAD;
            } else if (map.equals("3")) {
                CrmProduct p = (CrmProduct) hibernateTemplate.get(CrmProduct.class, refid);
                details = " Product - ";
                details += StringUtil.isNullOrEmpty(p.getProductname()) ? "" : p.getProductname();
                auditAction = AuditAction.PRODUCT_DOC_UPLOAD;
            } else if (map.equals("4")) {
                CrmAccount a = (CrmAccount) hibernateTemplate.get(CrmAccount.class, refid);
                details = " Account - ";
                details += StringUtil.isNullOrEmpty(a.getAccountname()) ? "" : a.getAccountname();
                auditAction = AuditAction.ACCOUNT_DOC_UPLOAD;
            } else if (map.equals("5")) {
                CrmOpportunity o = (CrmOpportunity) hibernateTemplate.get(CrmOpportunity.class, refid);
                details = " Opportunity - ";
                details += StringUtil.isNullOrEmpty(o.getOppname()) ? "" : o.getOppname();
                auditAction = AuditAction.OPPORTUNITY_DOC_UPLOAD;
            } else if (map.equals("6")) {
                CrmCase c = (CrmCase) hibernateTemplate.get(CrmCase.class, refid);
                details = " Case - ";
                details += StringUtil.isNullOrEmpty(c.getSubject()) ? "" : c.getSubject();
                auditAction = AuditAction.CASE_DOC_UPLOAD;
            } else if (map.equals("7")) {
                CrmActivityMaster am = (CrmActivityMaster) hibernateTemplate.get(CrmActivityMaster.class,
                        refid);
                details = " Activity - ";
                details += StringUtil.isNullOrEmpty(am.getFlag()) ? "" : am.getFlag() + " ";
                details += StringUtil.isNullOrEmpty(am.getCrmCombodataByStatusid().getValue()) ? ""
                        : am.getCrmCombodataByStatusid().getValue();
                auditAction = AuditAction.ACTIVITY_DOC_UPLOAD;
            } else if (map.equals("-1")) {
                details = " My - Document ";
                auditAction = AuditAction.MY_DOC_UPLOAD;
            }
            auditTrailDAOObj.insertAuditLog(auditAction,
                    " Docment: '" + doc.getDocname() + "' , uploaded for " + details, request, refid, id);
        }
        myjobj.put("ID", docID);
        txnManager.commit(status);
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        txnManager.rollback(status);
    } finally {
        // out.close();
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

From source file:com.siblinks.ws.service.impl.PlaylistServiceImpl.java

private boolean deletePlaylist(final String plid, final String uid) {
    boolean flag = false;

    TransactionDefinition def = new DefaultTransactionDefinition();
    TransactionStatus status = transactionManager.getTransaction(def);

    try {//from   w  ww  .  jav  a  2  s.co  m
        Object[] queryParams = { plid };

        dao.insertUpdateObject(SibConstants.SqlMapperBROT44.SQL_DELETE_PLAYLIST_VIDEO, queryParams);

        queryParams = new Object[] { plid, uid };
        dao.insertUpdateObject(SibConstants.SqlMapperBROT44.SQL_DELETE_PLAYLIST, queryParams);
        transactionManager.commit(status);
        flag = true;
    } catch (Exception e) {
        e.printStackTrace();
        flag = false;
        transactionManager.rollback(status);
    }
    return flag;
}

From source file:org.ohmage.query.impl.DocumentQueries.java

public String createDocument(byte[] contents, String name, String description,
        Document.PrivacyState privacyState, Map<String, Document.Role> campaignRoleMap,
        Map<String, Document.Role> classRoleMap, String creatorUsername) throws DataAccessException {

    // Create a new, random UUID to use to save this file.
    String uuid = UUID.randomUUID().toString();

    // getDirectory() is used as opposed to accessing the current leaf
    // directory class variable as it will do sanitation in case it hasn't
    // been initialized or is full.
    File documentDirectory = getDirectory();
    File newFile = new File(documentDirectory.getAbsolutePath() + "/" + uuid);
    String url = "file://" + newFile.getAbsolutePath();

    // Write the document to the file system.
    try {//  w w  w .  ja  va 2s  .c  o  m
        FileOutputStream os = new FileOutputStream(newFile);
        os.write(contents);
        os.flush();
        os.close();
    } catch (IOException e) {
        throw new DataAccessException("Error writing the new document to the system.", e);
    }
    long fileLength = newFile.length();

    // Parse the name and get the extension.
    String extension = getExtension(name);

    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Creating a new document.");

    try {
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        // Insert the file in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_DOCUMENT, new Object[] { uuid, name, description, extension,
                    url, fileLength, privacyState.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_DOCUMENT + "' with parameters: "
                    + uuid + ", " + name + ", " + description + ", " + extension + ", " + url + ", "
                    + fileLength + ", " + privacyState, e);
        }

        // Insert the creator in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_DOCUMENT_USER_CREATOR, new Object[] { uuid, creatorUsername });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_DOCUMENT_USER_CREATOR
                    + "' with parameters: " + uuid + ", " + creatorUsername, e);
        }

        // Insert this user's user-role in the DB.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER_ROLE,
                    new Object[] { uuid, creatorUsername, Document.Role.OWNER.toString() });
        } catch (org.springframework.dao.DataAccessException e) {
            if (newFile.delete()) {
                LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
            }
            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_INSERT_USER_ROLE + "' with parameters: "
                    + uuid + ", " + creatorUsername + ", " + Document.Role.OWNER, e);
        }

        // Insert any campaign associations in the DB.
        if (campaignRoleMap != null) {
            for (String campaignId : campaignRoleMap.keySet()) {
                // Attempt to insert it into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_ROLE,
                            new Object[] { uuid, campaignId, campaignRoleMap.get(campaignId).toString() });
                } catch (org.springframework.dao.DataAccessException e) {
                    if (newFile.delete()) {
                        LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
                    }
                    transactionManager.rollback(status);
                    throw new DataAccessException(
                            "Error executing SQL '" + SQL_INSERT_CAMPAIGN_ROLE + "' with parameters: " + uuid
                                    + ", " + campaignId + ", " + campaignRoleMap.get(campaignId),
                            e);
                }
            }
        }

        // Insert any class associations in the DB.
        if (classRoleMap != null) {
            for (String classId : classRoleMap.keySet()) {
                // Attempt to insert it into the database.
                try {
                    getJdbcTemplate().update(SQL_INSERT_CLASS_ROLE,
                            new Object[] { uuid, classId, classRoleMap.get(classId).toString() });
                } catch (org.springframework.dao.DataAccessException e) {
                    if (newFile.delete()) {
                        LOGGER.warn("Could not delete the file that was just created: " + newFile.toString());
                    }
                    transactionManager.rollback(status);
                    throw new DataAccessException("Error executing SQL '" + SQL_INSERT_CLASS_ROLE
                            + "' with parameters: " + uuid + ", " + classId + ", " + classRoleMap.get(classId),
                            e);
                }
            }
        }

        // Commit the transaction.
        try {
            transactionManager.commit(status);
        } catch (TransactionException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while committing the transaction.", e);
        }

        return uuid;
    } catch (TransactionException e) {
        throw new DataAccessException("Error while attempting to rollback the transaction.", e);
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAO.java

/**
 * NodeDAO Constructor. This class was developed and tested using a
 * Sybase ASE RDBMS. Some SQL (update commands in particular) may be non-standard.
 *
 * @param dataSource//from  w w w  .j  a  v a2  s .  com
 * @param nodeSchema
 * @param authority
 * @param identManager
 */
public NodeDAO(DataSource dataSource, NodeSchema nodeSchema, String authority, IdentityManager identManager,
        String deletedNodePath) {
    this.dataSource = dataSource;
    this.nodeSchema = nodeSchema;
    this.authority = authority;
    this.identManager = identManager;
    this.deletedNodePath = deletedNodePath;

    this.defaultTransactionDef = new DefaultTransactionDefinition();
    defaultTransactionDef.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_REPEATABLE_READ);
    this.dirtyReadTransactionDef = new DefaultTransactionDefinition();
    dirtyReadTransactionDef.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    this.jdbc = new JdbcTemplate(dataSource);
    this.transactionManager = new DataSourceTransactionManager(dataSource);

    this.dateFormat = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC);
    this.cal = Calendar.getInstance(DateUtil.UTC);
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*from   www  .  j  a v  a 2  s  .c o  m*/
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }
    // check that
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        boolean finded = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                finded = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(finded);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

From source file:org.mybatis.spring.MyBatisSpringTest.java

@Test
public void testWithJtaTxManagerAndNonSpringTxManager() throws java.sql.SQLException {
    Environment original = sqlSessionFactory.getConfiguration().getEnvironment();

    MockDataSource mockDataSource = new MockDataSource();
    mockDataSource.setupConnection(createMockConnection());

    Environment nonSpring = new Environment("non-spring", new ManagedTransactionFactory(), mockDataSource);
    sqlSessionFactory.getConfiguration().setEnvironment(nonSpring);

    JtaTransactionManager jtaManager = new JtaTransactionManager(new MockUserTransaction());

    DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
    txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED");

    TransactionStatus status = jtaManager.getTransaction(txDef);

    try {/*from   ww w .  ja  va 2  s.c  o  m*/
        session = SqlSessionUtils.getSqlSession(sqlSessionFactory);
        session.getMapper(TestMapper.class).findTest();
        // Spring is not managing SqlSession, so commit is needed
        session.commit(true);
        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

        jtaManager.commit(status);

        // assume a real JTA tx would enlist and commit the JDBC connection
        assertNoCommitJdbc();
        assertCommitSession();

        MockConnection mockConnection = (MockConnection) mockDataSource.getConnection();
        assertEquals("should call commit on Connection", 0, mockConnection.getNumberCommits());
        assertEquals("should not call rollback on Connection", 0, mockConnection.getNumberRollbacks());

        assertEquals("should not call DataSource.getConnection()", 0, dataSource.getConnectionCount());

    } finally {
        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

        sqlSessionFactory.getConfiguration().setEnvironment(original);

        // null the connection since it was not used
        // this avoids failing in validateConnectionClosed()
        connection = null;
    }
}