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:org.ohmage.query.impl.UserQueries.java

public void createUser(final String username, final String hashedPassword, final String emailAddress,
        final Boolean admin, final Boolean enabled, final Boolean newAccount,
        final Boolean campaignCreationPrivilege) throws DataAccessException {

    Boolean tAdmin = admin;/*from w ww.j av  a  2  s .c  o  m*/
    if (tAdmin == null) {
        tAdmin = false;
    }

    Boolean tEnabled = enabled;
    if (tEnabled == null) {
        tEnabled = false;
    }

    Boolean tNewAccount = newAccount;
    if (tNewAccount == null) {
        tNewAccount = true;
    }

    Boolean tCampaignCreationPrivilege = campaignCreationPrivilege;
    if (tCampaignCreationPrivilege == null) {
        try {
            tCampaignCreationPrivilege = PreferenceCache.instance()
                    .lookup(PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE).equals("true");
        } catch (CacheMissException e) {
            throw new DataAccessException("Cache doesn't know about 'known' value: "
                    + PreferenceCache.KEY_DEFAULT_CAN_CREATE_PRIVILIEGE, e);
        }
    }

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

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

        // Insert the new user.
        try {
            getJdbcTemplate().update(SQL_INSERT_USER, new Object[] { username, hashedPassword, emailAddress,
                    tAdmin, tEnabled, tNewAccount, tCampaignCreationPrivilege });
        } catch (org.springframework.dao.DataAccessException e) {
            transactionManager.rollback(status);
            throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_USER
                    + "' with parameters: " + username + ", " + hashedPassword + ", " + emailAddress + ", "
                    + tAdmin + ", " + tEnabled + ", " + tNewAccount + ", " + tCampaignCreationPrivilege, e);
        }

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

From source file:com.krawler.spring.crm.caseModule.crmCaseController.java

public ModelAndView saveCases(HttpServletRequest request, HttpServletResponse response)
        throws ServletException {
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;/*from ww  w  .  j  a va 2 s . c o  m*/
    CrmCase cases = 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 {
        boolean caseClosed = false;
        boolean assignedUserChanged = false;
        JSONObject jobj = new JSONObject(request.getParameter("jsondata"));
        String companyid = sessionHandlerImpl.getCompanyid(request);
        String userid = sessionHandlerImpl.getUserid(request);
        Integer operationCode = CrmPublisherHandler.ADDRECORDCODE;
        String id = jobj.getString("caseid");
        String[] arrayId = new String[] { id };
        jobj.put("userid", userid);
        jobj.put("companyid", companyid);
        jobj.put("updatedon", new Date().getTime());
        JSONArray jcustomarray = null;
        if (jobj.has("customfield")) {
            jcustomarray = jobj.getJSONArray("customfield");
        }
        if (id.equals("0")) {
            id = java.util.UUID.randomUUID().toString();
            jobj.put("caseid", id);
            jobj.put("casecreatedby", userid);
            kmsg = crmCaseDAOObj.addCases(jobj);
            cases = (CrmCase) kmsg.getEntityList().get(0);
            if (cases.getValidflag() == 1) {
                auditTrailDAOObj.insertAuditLog(AuditAction.CASE_CREATE,
                        ((cases.getSubject() == null) ? "" : cases.getSubject()) + " - Case created ", request,
                        id);
            }
            HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
            customrequestParams.put("customarray", jcustomarray);
            customrequestParams.put("modulename", Constants.Crm_Case_modulename);
            customrequestParams.put("moduleprimarykey", Constants.Crm_Caseid);
            customrequestParams.put("modulerecid", id);
            customrequestParams.put("companyid", companyid);
            customrequestParams.put("customdataclasspath", Constants.Crm_case_custom_data_classpath);
            if (jobj.has("customfield")) {
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult != null && customDataresult.getEntityList().size() > 0) {
                    jobj.put("CrmCaseCustomDataobj", id);
                    kmsg = crmCaseDAOObj.editCases(jobj);
                }
            }
            // fetch auto-number columns only
            HashMap<String, Object> fieldrequestParams = new HashMap<String, Object>();
            fieldrequestParams.put("isexport", true);
            fieldrequestParams.put("filter_names", Arrays.asList("companyid", "moduleid", "fieldtype"));
            fieldrequestParams.put("filter_values",
                    Arrays.asList(companyid, Constants.Crm_case_moduleid, Constants.CUSTOM_FIELD_AUTONUMBER));
            KwlReturnObject AutoNoFieldMap = fieldManagerDAOobj.getFieldParams(fieldrequestParams);

            // increment auto number if exist
            if (AutoNoFieldMap.getEntityList().size() > 0) {
                JSONArray autoNoData = fieldDataManagercntrl.setAutoNumberCustomData(customrequestParams,
                        AutoNoFieldMap.getEntityList());
                jobj.put(com.krawler.common.util.Constants.AUTOCUSTOMFIELD, autoNoData);
            } // END logic - auto no
        } else {
            operationCode = CrmPublisherHandler.UPDATERECORDCODE;
            // using old and new record validflag, check record becames valid or not
            List<String> recordIds = new ArrayList<String>();
            recordIds.add(id);
            List<CrmCase> oldCaseRecord = crmCaseDAOObj.getCases(recordIds);
            String caseAssignedId = null;
            if (oldCaseRecord != null) {
                for (CrmCase caseObj : oldCaseRecord) {
                    caseAssignedId = (caseObj.getAssignedto() != null ? caseObj.getAssignedto().getUserID()
                            : "");
                    if (jobj.has("caseassignedtoid")) {
                        if (!caseAssignedId.equals(jobj.getString("caseassignedtoid"))) {
                            assignedUserChanged = true;
                        }
                    }
                    if (caseObj.getCrmCombodataByCasestatusid() != null && caseObj
                            .getCrmCombodataByCasestatusid().getMainID().equals(Constants.CASESTATUS_CLOSED)) {
                        caseClosed = true;
                    }
                }
            }
            if (jobj.has("customfield")) {

                HashMap<String, Object> customrequestParams = new HashMap<String, Object>();
                customrequestParams.put("customarray", jcustomarray);
                customrequestParams.put("modulename", Constants.Crm_Case_modulename);
                customrequestParams.put("moduleprimarykey", Constants.Crm_Caseid);
                customrequestParams.put("modulerecid", id);
                customrequestParams.put("companyid", companyid);
                customrequestParams.put("customdataclasspath", Constants.Crm_case_custom_data_classpath);
                KwlReturnObject customDataresult = fieldDataManagercntrl.setCustomData(customrequestParams);
                if (customDataresult != null && customDataresult.getEntityList().size() > 0) {
                    jobj.put("CrmCaseCustomDataobj", id);
                }
            }
            if (jobj.has("createdon")) {
                jobj.put("createdon", jobj.getLong("createdon"));
            }
            kmsg = crmCaseDAOObj.editCases(jobj);
            cases = (CrmCase) kmsg.getEntityList().get(0);
            if (cases.getValidflag() == 1) {
                auditTrailDAOObj.insertAuditLog(AuditAction.CASE_UPDATE, jobj.getString("auditstr") + " Case - "
                        + ((cases.getSubject() == null) ? "" : cases.getSubject()) + " ", request, id);

                String loginURL = URLUtil.getRequestPageURL(request, Links.loginpageFull);
                HashMap<String, Object> extraParams = new HashMap<String, Object>();
                extraParams.put(NotificationConstants.LOGINURL, loginURL);
                extraParams.put(NotificationConstants.PARTNERNAME, sessionHandlerImplObj.getPartnerName());
                if (jobj.has("casestatusid") && !caseClosed && cases.getCrmCombodataByCasestatusid() != null
                        && cases.getCrmCombodataByCasestatusid().getMainID()
                                .equals(Constants.CASESTATUS_CLOSED)) {
                    sendNotificationOnCaseClosed(cases, userid, companyid, extraParams,
                            sessionHandlerImplObj.getSystemEmailId());
                }
                if (assignedUserChanged && cases.getAssignedto() != null) {
                    sendNotificationOnCaseAssigned(cases, userid, extraParams);
                }
            }
        }
        if (request.getParameter("massEdit") != null
                && Boolean.parseBoolean(request.getParameter("massEdit"))) {
            if (arrayId[0].equals("0"))
                crmCommonService.validateMassupdate(new String[] { cases.getCaseid() }, "Case", companyid);
            else
                crmCommonService.validateMassupdate(arrayId, "Account", companyid);
        }
        myjobj.put("success", true);
        myjobj.put("ID", cases.getCaseid());
        myjobj.put("createdon", jobj.has("createdon") ? jobj.getLong("createdon") : "");
        myjobj.put(com.krawler.common.util.Constants.AUTOCUSTOMFIELD,
                jobj.has(com.krawler.common.util.Constants.AUTOCUSTOMFIELD)
                        ? jobj.getJSONArray(com.krawler.common.util.Constants.AUTOCUSTOMFIELD)
                        : "");
        txnManager.commit(status);

        JSONObject cometObj = jobj;
        if (!StringUtil.isNullObject(cases)) {
            if (!StringUtil.isNullObject(cases.getCreatedon())) {
                cometObj.put("createdon", cases.getCreatedonGMT());
            }
        }
        publishCasesModuleInformation(request, cometObj, operationCode, companyid, userid);
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
}

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

@Test
public void testSqlSessionCommitWithTx() {
    DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
    txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED");

    TransactionStatus status = txManager.getTransaction(txDef);

    session = SqlSessionUtils.getSqlSession(sqlSessionFactory);
    session.getMapper(TestMapper.class).findTest();
    // commit should no-op since there is an active transaction
    session.commit(true);//  ww w  .  j a v  a 2  s.c o m
    SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

    txManager.commit(status);

    // Connection should be committed once, but we explicitly called commit on the SqlSession,
    // so it should be committed twice
    assertEquals("should call commit on Connection", 1, connection.getNumberCommits());
    assertEquals("should not call rollback on Connection", 0, connection.getNumberRollbacks());
    assertEquals("should call commit on SqlSession", 2, executorInterceptor.getCommitCount());
    assertEquals("should not call rollback on SqlSession", 0, executorInterceptor.getRollbackCount());

    assertSingleConnection();
}

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

@Override
public void deleteAnnotation(final UUID annotationId) throws DataAccessException {
    // Create the transaction.
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("Deleting an annotation.");

    try {//w  ww.  ja v a  2  s . co m
        // Begin the transaction.
        PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            getJdbcTemplate().update(SQL_DELETE_ANNOTATION, annotationId.toString());
        } catch (org.springframework.dao.DataAccessException e) {

            transactionManager.rollback(status);
            throw new DataAccessException("Error executing SQL '" + SQL_DELETE_ANNOTATION + "' with parameter: "
                    + annotationId.toString(), e);
        }

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

From source file:com.poscoict.license.service.ManagementService.java

public void changeUserStatus(String objectId, String uStatus, String userNo) {
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {/*from  w ww  .  j  ava 2  s .co m*/
        managementDao.changeUserStatus(objectId, Consts.ProgressStatus.valueOf(uStatus).getProgressStatus(),
                userNo);
        managementDao.insertProgressUserLog(objectId, null,
                Consts.ProgressStatus.valueOf(uStatus).getProgressStatus(), userNo);
        this.transactionManager.commit(status);
    } catch (Exception e) {
        this.transactionManager.rollback(status);
        logger.error("changeUserStatus: ", e);
    }
}

From source file:edu.jhuapl.openessence.datasource.jdbc.entry.JdbcOeDataEntrySource.java

/**
 * **************************************************************************************************************
 * [C]RUD - Create/Add methods for Data Entry **************************************************************************************************************
 *///from   ww  w .  ja  va2 s  .c  om

@Override
public Map<String, Object> addCompleteRecord(CompleteRecord completeRecord, boolean ignoreSpecialSql)
        throws OeDataSourceAccessException {
    TransactionDefinition def = new DefaultTransactionDefinition();
    TransactionStatus status = getTransactionManager().getTransaction(def);
    Map<String, Object> FOREIGN_KEY_VALUE_MAP = new HashMap<String, Object>();

    TableAwareQueryRecord parent = completeRecord.getParentRecord();
    try {
        // 1. add parent record and get the pk-keys for this record entry. pk-keys get passed to children for their fk-keys
        Map<String, Object> parentKeys = addQueryRecord(parent, ignoreSpecialSql);
        DbKeyValMap fkIdMap = new DbKeyValMap(parentKeys);

        // 2. get dimension Id correlation for parentpkIds <--> childpkIds so INSERTs to child tables use correct dimensionId
        Collection<ChildRecordSet> allChildRecSets = completeRecord.getChildrenRecordSets();
        Map<String, ChildRecordSet> childRecSetMap = new HashMap<String, ChildRecordSet>();
        for (ChildRecordSet crs : allChildRecSets) {
            childRecSetMap.put(crs.getChildTableName(), crs);
        }
        Iterator<ChildRecordSet> childRecSetsIter = allChildRecSets.iterator();

        if (childTableMap != null && allChildRecSets.size() > 0) {

            while (childRecSetsIter.hasNext()) {
                Map<String, String> pksFromParent = null;
                ChildTableDetails childTableDetails = childTableMap
                        .get(childRecSetsIter.next().getChildTableName());

                if (childTableDetails != null) {
                    pksFromParent = childTableDetails.getPksFromParentToChild();
                }

                // 3. setup fkIds-Values for the children
                if (pksFromParent != null) {
                    for (String fk : pksFromParent.keySet()) {
                        // i.e. from MasterID --> c1_MasterID & ReportID --> c1_ReportID
                        FOREIGN_KEY_VALUE_MAP.put(pksFromParent.get(fk), fkIdMap.get(fk));
                    }
                }

                // 4. for each childRecordSet, add its children records
                Collection<TableAwareQueryRecord> childrenRecords = childRecSetMap
                        .get(childTableDetails.getTableName()).getChildRecords();
                for (TableAwareQueryRecord child : childrenRecords) {
                    addChildRecord(child, ignoreSpecialSql, FOREIGN_KEY_VALUE_MAP);
                }
                // need to clear old pk/fk dimension Ids for each child table
                FOREIGN_KEY_VALUE_MAP.clear();

            }
        } else if (childTableMap == null && allChildRecSets.size() > 0) {
            throw new OeDataSourceAccessException(
                    "No data was added. Childtablemap is empty, but childrecordsets were found on this record. Childtables not configured in groovy datasource definition.");
        }

        getTransactionManager().commit(status);
        return parentKeys;

    } catch (DuplicateKeyException dae) {
        getTransactionManager().rollback(status);
        throw new OeDataSourceAccessException(
                "Error: No data was added. Could not create record due to duplicate key(s).");
    } catch (DataAccessException dae) {
        getTransactionManager().rollback(status);
        throw new OeDataSourceAccessException(
                "No data was added. DataAccessException occurred while trying to add a complete record.", dae);
    } catch (Exception e) {
        getTransactionManager().rollback(status);
        throw new OeDataSourceAccessException(
                "No data was added. Problem occurred while trying to add a complete record.", e);
    }
}

From source file:com.krawler.esp.handlers.zohoRequestHandler.java

public String saveUpdateZohoLeads(String username, String password, String authToken, String userid,
        String companyid) {/*w  w  w .jav  a  2s .co  m*/

    //        Session s = zohoRequestDAO.getCurrentSession();
    String result = "{success:false,recCount:0,totalRecords:0}";
    int recCount = 0;
    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 {

        String Hql = "from CrmLead c where  c.leadid= ?";
        JSONObject jobj = getRecordJson("Leads", username, password, authToken); //Potential , Leads, Accounts
        if (jobj.get("success").equals(true)) {

            JSONArray dataArray = jobj.getJSONArray("data");
            for (int cnt = 0; cnt < dataArray.length(); cnt++) {
                //                    Transaction tx = (Transaction) hibernateTemplate.beginTransaction();
                JSONObject recObj = dataArray.getJSONObject(cnt);
                List existingContact = zohoRequestDAO.executeQuery(Hql, new Object[] { recObj.get("LEADID") });

                JSONObject jobjret = new JSONObject();
                String fname = recObj.getString("First Name");
                String lname = recObj.getString("Last Name");
                lname = fname.equalsIgnoreCase("null") ? lname : fname + " " + lname;
                lname = lname.trim();
                jobjret.put("lastname", recObj.getString("Last Name").equals("null") ? "" : lname);
                jobjret.put("email", recObj.getString("Email").equals("null") ? "" : recObj.getString("Email"));
                jobjret.put("phone", recObj.getString("Phone").equals("null") ? "" : recObj.getString("Phone"));
                jobjret.put("validflag", 1);
                jobjret.put("userid", userid);
                jobjret.put("companyid", companyid);
                jobjret.put("isconverted", "0");
                jobjret.put("istransfered", "0");
                jobjret.put("type", "0");
                jobjret.put("updatedon", new Date());
                jobjret.put("leadid", recObj.getString("LEADID"));
                jobjret.put("leadownerid", userid);
                jobjret.put("isarchive", false);
                jobjret.put("deleteflag", 0);

                if (existingContact.size() > 0) {
                    KwlReturnObject kmsg = crmLeadDAOObj.editLeads(jobjret);
                } else {
                    KwlReturnObject kmsg = crmLeadDAOObj.addLeads(jobjret);
                }
                recCount++;
            }
            txnManager.commit(status);
            result = "{success:true,recCount:" + recCount + ",totalRecords:" + jobj.get("recordCount") + "}";
        }
    } catch (ServiceException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        txnManager.rollback(status);
    } finally {
        //            s.close();
        return result;
    }
}

From source file:com.poscoict.license.service.ManagementService.java

@SuppressWarnings("unchecked")
public void newContract(ContractPersonInfo per, ContractProductInfo pro, String[] etcFile, HttpSession session)
        throws UserException {
    logger.info("newContract");
    TransactionStatus status = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
    try {/*from  w  w w .  ja  v  a2s  .c om*/
        System.out.println("company: " + per.getORDER_COMPANY_CODE());
        String licenseUpPath = Consts.LICENSE_FILE_HOME;

        String userNo = per.getUSER_NO();

        if (pro != null) {
            ArrayList<MultipartFile> upFileList = (ArrayList<MultipartFile>) pro.getFile();
            ArrayList<String> productList = (ArrayList<String>) pro.getPRODUCT_FILE_ID();
            ArrayList<String> licenseKeyList = (ArrayList<String>) pro.getLICENSE_KEY();
            ArrayList<String> quantityList = (ArrayList<String>) pro.getLICENSE_QUANTITY();
            ArrayList<String> fileCheckList = (ArrayList<String>) pro.getCHECKBOX();

            for (int i = 0; i < productList.size(); i++) {
                String licensePath = "";

                String licenseName = "";
                String objectId = productList.get(i);
                String licenseKey = licenseKeyList.get(i);
                String quantity = quantityList.get(i);
                String fileCheck = fileCheckList.get(i);
                if (fileCheck.equals("false")) {
                    MultipartFile upFile = upFileList.get(i);
                    licenseName = upFile.getOriginalFilename(); // ???
                    logger.info("newContract: fileName= " + licenseName);
                    try {
                        File upfile = new File(licenseUpPath + userNo + File.separator + licenseName);

                        if (upfile.isFile())
                            throw new UserException(
                                    "???? . ??  .");

                        if (!upfile.exists())
                            upfile.mkdirs();

                        upFile.transferTo(upfile);
                        licensePath = upfile.getAbsolutePath();
                        logger.info("newContract: licensePath= " + licensePath);
                    } catch (IOException e) {
                        logger.error("newContract(File Upload Error): ", e);
                    }
                    // ?? 
                }
                managementDao.addLicenseInfo(userNo, licenseKey, objectId,
                        (String) session.getAttribute("USER_NO"), licensePath, licenseName, quantity);
            }
        }
        if (etcFile != null) {
            for (int i = 0; i < etcFile.length; i++) {
                String etcId = etcFile[i];
                managementDao.addUserEtcFileInfo(userNo, etcId, (String) session.getAttribute("USER_NO"));
            }
        }

        //  
        managementDao.addUser(per, (String) session.getAttribute("USER_NO"), passwordEncoder(userNo),
                Consts.USERLV_PUBLIC);
        //   
        Map<String, Object> map = getClientPermission();
        String codes = (String) map.get("codes");
        String codeTypes = (String) map.get("codeTypes");
        int size = (Integer) map.get("size");

        logger.info("codes : " + codes);
        logger.info("codeTypes : " + codeTypes);
        logger.info("size : " + size);
        logger.info("userNo : " + userNo);

        managementDao.insert_user_permission(codes, codeTypes, userNo, size);

        // ??  ??
        if (!per.getPRODUCT_SETUP_DATE().isEmpty()) {
            managementDao.updateProductSetupDate(userNo, per.getPRODUCT_SETUP_DATE());
        }
        this.transactionManager.commit(status);
    } catch (DuplicateKeyException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
        throw new DuplicateKeyException(
                " ?. ?? ? .");
    } catch (RuntimeException e) {
        this.transactionManager.rollback(status);
        logger.error("plusProduct: ", e);
    }

    //        return "redirect:/management";
}

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

@Test
public void testWithInterleavedTx() throws Exception {
    // this session will use one Connection
    session = SqlSessionUtils.getSqlSession(sqlSessionFactory);
    session.getMapper(TestMapper.class).findTest();

    // this transaction should use another Connection
    TransactionStatus status = txManager.getTransaction(new DefaultTransactionDefinition());

    // session continues using original connection
    session.getMapper(TestMapper.class).insertTest("test2");
    session.commit(true);//from w  w w  .  j a va2  s .  c  om
    SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);

    // this should succeed
    // SpringManagedTransaction (from SqlSession.commit()) should not interfere with tx
    txManager.commit(status);

    // two DB connections should have completed, each using their own Connection
    assertEquals("should call DataSource.getConnection() twice", 2, dataSource.getConnectionCount());

    // both connections should be committed
    assertEquals("should call commit on Connection 1", 1, connection.getNumberCommits());
    assertEquals("should not call rollback on Connection 1", 0, connection.getNumberRollbacks());

    assertEquals("should call commit on Connection 2", 1, connectionTwo.getNumberCommits());
    assertEquals("should not call rollback on Connection 2", 0, connectionTwo.getNumberRollbacks());

    // the SqlSession should have also committed and executed twice
    assertCommitSession();
    assertExecuteCount(2);

    assertConnectionClosed(connection);
    assertConnectionClosed(connectionTwo);
}