List of usage examples for org.springframework.transaction.support DefaultTransactionDefinition DefaultTransactionDefinition
public DefaultTransactionDefinition()
From source file:com.siblinks.ws.service.impl.CategoryServiceImpl.java
/** * {@inheritDoc}// w w w . j av a2 s. c o m * */ @Override @RequestMapping("/updateCategory") public ResponseEntity<Response> updateCategoryData(@RequestBody final ManageSubjectModel request) throws Exception { logger.info("updateMenuData " + new Date()); TransactionDefinition def = new DefaultTransactionDefinition(); TransactionStatus status = transactionManager.getTransaction(def); String userId = "6";// logged.getLoggedInUser().getUserid(); try { // Update menu dao.insertUpdateObject(SibConstants.SqlMapper.SQL_UPDATE_CATEGORY_DATA, new Object[] { request.getName(), request.getImage(), request.getDescription(), request.getStatus(), request.getDisplaySort(), userId, request.getId() }); transactionManager.commit(status); logger.info("updateMenu success " + new Date()); } catch (NullPointerException | DataAccessException e) { transactionManager.rollback(status); throw e; } SimpleResponse reponse = new SimpleResponse("" + Boolean.TRUE, ""); ResponseEntity<Response> entity = new ResponseEntity<Response>(reponse, HttpStatus.OK); return entity; }
From source file:org.mybatis.spring.MyBatisSpringTest.java
@Test public void testNonSpringTxFactoryNonSpringDSWithTx() throws java.sql.SQLException { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setupConnection(createMockConnection()); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), mockDataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null;/*from ww w . j av a 2s . c o m*/ try { status = txManager.getTransaction(new DefaultTransactionDefinition()); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.commit(); session.close(); txManager.commit(status); // txManager still uses original connection assertCommit(); assertSingleConnection(); // SqlSession uses its own connection // that connection will not have commited since no SQL was executed by the session MockConnection mockConnection = (MockConnection) mockDataSource.getConnection(); assertEquals("should call commit on Connection", 0, mockConnection.getNumberCommits()); assertEquals("should not call rollback on Connection", 0, mockConnection.getNumberRollbacks()); assertCommitSession(); } finally { SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:es.upm.fiware.rss.dao.impl.test.DbeTransactionDaoImplTest.java
@Transactional(propagation = Propagation.SUPPORTS) public void testDeleteTransactionsByProviderId() { int txTransactionId = 1; String providerId = new String("provider"); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(Propagation.REQUIRES_NEW.value()); TransactionStatus status = transactionManager.getTransaction(def); dbeTransactionDAO.deleteTransactionsByProviderId(providerId); transactionManager.commit(status);// w w w .j a v a2 s .c o m List<DbeTransaction> listDbeTr = dbeTransactionDAO.getTransactionsByProviderId(providerId); if (listDbeTr != null && listDbeTr.size() > 0) { DbeTransactionDaoImplTest.LOGGER.debug("looking result list data...."); DbeTransactionDaoImplTest.LOGGER.error("Obtained:" + listDbeTr.get(0).getTxTransactionId()); Assert.assertTrue("0 data obtained ", listDbeTr.get(0).getTxTransactionId() == txTransactionId); } else { DbeTransactionDaoImplTest.LOGGER.debug("Obtained 0 data is not possible with datatest values"); Assert.assertTrue("0 data obtained ", true); } }
From source file:org.ohdsi.webapi.feasibility.PerformFeasibilityTasklet.java
@Override public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) throws Exception { Date startTime = Calendar.getInstance().getTime(); Map<String, Object> jobParams = chunkContext.getStepContext().getJobParameters(); Integer studyId = Integer.valueOf(jobParams.get("study_id").toString()); Integer sourceId = Integer.valueOf(jobParams.get("source_id").toString()); boolean isValid = false; DefaultTransactionDefinition requresNewTx = new DefaultTransactionDefinition(); requresNewTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus initStatus = this.transactionTemplate.getTransactionManager() .getTransaction(requresNewTx); FeasibilityStudy study = this.feasibilityStudyRepository.findOne(studyId); CohortDefinition resultDef = study.getResultRule(); if (resultDef != null) { CohortGenerationInfo resultInfo = findCohortGenerationInfoBySourceId(resultDef.getGenerationInfoList(), sourceId);/* w w w . j av a 2 s.com*/ resultInfo.setIsValid(false).setStatus(GenerationStatus.RUNNING).setStartTime(startTime) .setExecutionDuration(null); } StudyGenerationInfo studyInfo = findStudyGenerationInfoBySourceId(study.getStudyGenerationInfoList(), sourceId); studyInfo.setIsValid(false); studyInfo.setStartTime(startTime); studyInfo.setStatus(GenerationStatus.RUNNING); this.feasibilityStudyRepository.save(study); this.transactionTemplate.getTransactionManager().commit(initStatus); try { final int[] ret = this.transactionTemplate.execute(new TransactionCallback<int[]>() { @Override public int[] doInTransaction(final TransactionStatus status) { return doTask(chunkContext); } }); log.debug("Update count: " + ret.length); isValid = true; } catch (final TransactionException e) { isValid = false; log.error(e.getMessage(), e); throw e;//FAIL job status } finally { TransactionStatus completeStatus = this.transactionTemplate.getTransactionManager() .getTransaction(requresNewTx); Date endTime = Calendar.getInstance().getTime(); study = this.feasibilityStudyRepository.findOne(studyId); resultDef = study.getResultRule(); if (resultDef != null) { CohortGenerationInfo resultInfo = findCohortGenerationInfoBySourceId( resultDef.getGenerationInfoList(), sourceId); resultInfo = findCohortGenerationInfoBySourceId(resultDef.getGenerationInfoList(), sourceId); resultInfo.setIsValid(isValid); resultInfo.setExecutionDuration(new Integer((int) (endTime.getTime() - startTime.getTime()))); resultInfo.setStatus(GenerationStatus.COMPLETE); } studyInfo = findStudyGenerationInfoBySourceId(study.getStudyGenerationInfoList(), sourceId); studyInfo.setIsValid(isValid); studyInfo.setExecutionDuration(new Integer((int) (endTime.getTime() - startTime.getTime()))); studyInfo.setStatus(GenerationStatus.COMPLETE); this.feasibilityStudyRepository.save(study); this.transactionTemplate.getTransactionManager().commit(completeStatus); } return RepeatStatus.FINISHED; }
From source file:com.googlecode.starflow.engine.support.TriggerProcessEventUtil.java
/** * ?// ww w. ja va 2s. c om * * @param processInstId * @param action * @return */ private static void executeLogicInNewTransaction(ProcessDefine processDefine, ProcessInstance processInstance, IAction action) { PlatformTransactionManager txManager = ApplicationContextHolder.getBean(PlatformTransactionManager.class); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status = txManager.getTransaction(definition); try { action.execute(processDefine, processInstance); txManager.commit(status); } catch (Exception e) { txManager.rollback(status); throw new ProcessEngineException("?", e); } }
From source file:com.bleum.canton.jms.dao.impl.JMSTaskDao.java
@Override public void updateErrorTask(JMSTask task, int maxRetry) { DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); TransactionStatus tstatus = platformTransactionManager.getTransaction(paramTransactionDefinition); try {// w w w. j a v a 2 s. com if (task.getRetry() >= maxRetry) { this.jdbcTemplate.update(UPDATE_TASK_FATAL, task.getLastError(), new Date(), task.getId()); } else { this.jdbcTemplate.update(UPDATE_TASK_ERROR, task.getRetry() + 1, task.getLastError(), new Date(), task.getId()); } platformTransactionManager.commit(tstatus); } catch (Exception e) { platformTransactionManager.rollback(tstatus); } }
From source file:org.ohmage.query.impl.ImageQueries.java
@Override public void deleteImage(UUID imageId) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Deleting an image."); try {//from w ww . ja v a 2s. c o m // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); URL imageUrl = getImageUrl(imageId); try { getJdbcTemplate().update(SQL_DELETE_IMAGE, new Object[] { imageId.toString() }); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error executing SQL '" + SQL_DELETE_IMAGE + "' with parameter: " + imageId, e); } if (imageUrl != null) { deleteImageDiskOnly(imageUrl); } // 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:org.ohmage.query.impl.AuditQueries.java
@Override public void createAudit(final RequestServlet.RequestType requestType, final String uri, final String client, final String requestId, final String deviceId, final Map<String, String[]> parameters, final Map<String, String[]> extras, final String response, final long receivedMillis, final long respondMillis) throws DataAccessException { if (requestType == null) { throw new IllegalArgumentException("The request type is required and cannot be null."); } else if (uri == null) { throw new IllegalArgumentException("The request URI is required and cannot be null."); } else if (response == null) { throw new IllegalArgumentException("The response is required and cannot be null."); }//from ww w . java2 s. c o m // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a request audit."); try { // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // Create a key holder that will be responsible for referencing // which row was just inserted. KeyHolder keyHolder = new GeneratedKeyHolder(); // Insert the audit entry. try { getJdbcTemplate().update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(SQL_INSERT_AUDIT, new String[] { "id" }); ps.setString(1, requestType.name().toLowerCase()); ps.setString(2, uri); ps.setString(3, client); ps.setString(4, requestId); ps.setString(5, deviceId); ps.setString(6, response); ps.setLong(7, receivedMillis); ps.setLong(8, respondMillis); return ps; } }, keyHolder); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_AUDIT + "' with parameters: " + requestType.name().toLowerCase() + ", " + uri + ", " + client + ", " + deviceId + ", " + response + ", " + receivedMillis + ", " + respondMillis, e); } // Add all of the parameters. if (parameters != null) { for (String key : parameters.keySet()) { for (String value : parameters.get(key)) { try { getJdbcTemplate().update(SQL_INSERT_PARAMETER, keyHolder.getKey().longValue(), key, value); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error while executing SQL '" + SQL_INSERT_PARAMETER + "' with parameters: " + keyHolder.getKey().longValue() + ", " + key + ", " + value, e); } } } } // Add all of the extras. if (extras != null) { for (String key : extras.keySet()) { for (String value : extras.get(key)) { try { getJdbcTemplate().update(SQL_INSERT_EXTRA, keyHolder.getKey().longValue(), key, value); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException( "Error while executing SQL '" + SQL_INSERT_EXTRA + "' with parameters: " + keyHolder.getKey().longValue() + ", " + key + ", " + value, 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:dk.nsi.haiba.minipasconverter.dao.impl.MinipasHAIBADAOImpl.java
@Override public void setupTransaction() { transactionStatus = transactionManager.getTransaction(new DefaultTransactionDefinition()); }
From source file:org.ohmage.query.impl.AnnotationQueries.java
@Override public void createPromptResponseAnnotation(final UUID annotationId, final String client, final Long time, final DateTimeZone timezone, final String annotationText, Integer promptResponseId) throws DataAccessException { // Create the transaction. DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("Creating a new prompt response annotation."); try {/*from w ww.j ava2 s. c o m*/ // Begin the transaction. PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); long id = 0; try { id = insertAnnotation(annotationId, time, timezone, client, annotationText); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_ANNOTATION + "' with parameters: " + annotationId + ", " + time + ", " + timezone.getID() + ", " + client + ", " + ((annotationText.length() > 25) ? annotationText.substring(0, 25) + "..." : annotationText), e); } try { // Insert the link between the prompt_response and its annotation getJdbcTemplate().update(SQL_INSERT_PROMPT_RESPONSE_ANNOTATION, promptResponseId, id); } catch (org.springframework.dao.DataAccessException e) { transactionManager.rollback(status); throw new DataAccessException("Error while executing SQL '" + SQL_INSERT_PROMPT_RESPONSE_ANNOTATION + "' with parameters: " + promptResponseId + ", " + id, 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); } }