org.springframework.transaction.support.TransactionCallback Java Examples
The following examples show how to use
org.springframework.transaction.support.TransactionCallback.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TargetInstanceDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
/** @see TargetInstanceDAO#delete(Object). */ public void delete(final Object aObject) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { log.debug("Before Delete Object"); getSession().delete(aObject); log.debug("After Delete Object"); } catch(Exception ex) { log.warn("Setting Rollback Only"); ts.setRollbackOnly(); } return null; } } ); }
Example #2
Source File: MybatisTest.java From azeroth with Apache License 2.0 | 6 votes |
@Test public void testRwRouteWithTransaction2() { mapper.findByStatus((short) 1); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { mapper.findByStatus((short) 2); UserEntity entity = new UserEntity(); entity.setCreatedAt(new Date()); entity.setEmail(RandomStringUtils.random(6, true, true) + "@163.com"); entity.setMobile("13800" + RandomUtils.nextLong(100000, 999999)); entity.setType((short) 1); entity.setStatus((short) 1); mapper.insert(entity); mapper.findByStatus((short) 2); return null; } }); System.out.println(); }
Example #3
Source File: WebSphereUowTransactionManagerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void propagationNeverFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown IllegalTransactionStateException"); } catch (IllegalTransactionStateException ex) { // expected } }
Example #4
Source File: JTAFlexyPoolTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
@Test @Ignore public void test() throws InterruptedException, ExecutionException { long startNanos = System.nanoTime(); while (TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNanos) < seconds){ List<Future<Void>> futures = new ArrayList<>(); for (int i = 0; i < threadCount; i++) { futures.add(executorService.submit((Callable<Void>) () -> { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { for (int j = 0; j < 1000; j++) { entityManager.persist(new FlexyPoolEntities.Post()); } entityManager.createQuery("select count(p) from Post p").getSingleResult(); return null; }); return null; })); } for (Future<Void> future : futures) { future.get(); } } }
Example #5
Source File: WebSphereUowTransactionManagerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void uowManagerFoundInJndi() { MockUOWManager manager = new MockUOWManager(); ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate(WebSphereUowTransactionManager.DEFAULT_UOW_MANAGER_NAME, manager); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(); ptm.setJndiTemplate(jndiTemplate); ptm.afterPropertiesSet(); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); assertEquals("result", ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } })); assertEquals(UOWManager.UOW_TYPE_GLOBAL_TRANSACTION, manager.getUOWType()); assertFalse(manager.getJoined()); assertFalse(manager.getRollbackOnly()); }
Example #6
Source File: WebSphereUowTransactionManagerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void propagationNeverFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown IllegalTransactionStateException"); } catch (IllegalTransactionStateException ex) { // expected } }
Example #7
Source File: StageSqlMapDao.java From gocd with Apache License 2.0 | 6 votes |
@Override public Stage save(final Pipeline pipeline, final Stage stage) { return (Stage) transactionTemplate.execute((TransactionCallback) status -> { transactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { @Override public void afterCommit() { String pipelineName = pipeline.getName(); String stageName = stage.getName(); clearStageHistoryPageCaches(stage, pipelineName, false); clearCachedStage(stage.getIdentifier()); clearCachedAllStages(pipelineName, pipeline.getCounter(), stageName); removeFromCache(cacheKeyForStageCountForGraph(pipelineName, stageName)); } }); stage.setPipelineId(pipeline.getId()); int maxStageCounter = getMaxStageCounter(pipeline.getId(), stage.getName()); stage.setCounter(maxStageCounter + 1); getSqlMapClientTemplate().update("markPreviousStageRunsAsNotLatest", arguments("stageName", stage.getName()).and("pipelineId", pipeline.getId()).asMap()); getSqlMapClientTemplate().insert("insertStage", stage); stage.setIdentifier(new StageIdentifier(pipeline, stage)); return stage; }); }
Example #8
Source File: SpringJpaTest.java From hypersistence-optimizer with Apache License 2.0 | 6 votes |
@Before public void init() { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { Tag hibernate = new Tag(); hibernate.setName("hibernate"); entityManager.persist(hibernate); Tag jpa = new Tag(); jpa.setName("jpa"); entityManager.persist(jpa); return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } }
Example #9
Source File: PatchForUpdatingTagsJson_J10020.java From ranger with Apache License 2.0 | 6 votes |
@Override public void run() { errorMsg = txTemplate.execute(new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { String ret = null; try { if (serviceResource != null) { portServiceResource(serviceResource); } if (tag != null) { portTag(tag); } if (tagDef != null) { portTagDef(tagDef); } } catch (Throwable e) { logger.error("Port failed :[serviceResource=" + serviceResource + ", tag=" + tag + ", tagDef=" + tagDef +"]", e); ret = e.toString(); } return ret; } }); }
Example #10
Source File: SpringHibernateTest.java From hypersistence-optimizer with Apache License 2.0 | 6 votes |
@Before public void init() { hypersistenceOptimizer = new HypersistenceOptimizer( new HibernateConfig( sessionFactory ) ); try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { Tag hibernate = new Tag(); hibernate.setName("hibernate"); sessionFactory.getCurrentSession().persist(hibernate); Tag jpa = new Tag(); jpa.setName("jpa"); sessionFactory.getCurrentSession().persist(jpa); return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } }
Example #11
Source File: CommonsContentProducer.java From sakai with Educational Community License v2.0 | 6 votes |
public String getUrl(String ref) { return transactionTemplate.execute(new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { CommonsReferenceReckoner.CommonsReference r = CommonsReferenceReckoner.reckoner().reference(ref).reckon(); try { Site site = siteService.getSite(r.getContext()); ToolConfiguration fromTool = site.getToolForCommonId("sakai.commons"); return serverConfigurationService.getPortalUrl() + "/directtool/" + fromTool.getId() + "?ref=" + ref; } catch (Exception e) { log.error("Failed to get deep link for context {} and post {}. Returning empty string.", r.getContext(), r.getPostId(), e); } return ""; } }); }
Example #12
Source File: TargetInstanceDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
/** * Delete TargetInstances for the specified Target and Schedule * @param targetOid The target OID. * @param scheduleOid The schedule OID. */ public void deleteScheduledInstances(final Long targetOid, final Long scheduleOid) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { log.debug("Before deleting scheduled instance for " + targetOid + " " + scheduleOid); getSession().createQuery("DELETE TargetInstance WHERE state=:state AND schedule.oid=:scheduleOid AND target.oid=:targetOid") .setString("state", TargetInstance.STATE_SCHEDULED) .setLong("scheduleOid", scheduleOid) .setLong("targetOid", targetOid) .executeUpdate(); log.debug("After deleting scheduled instance for " + targetOid + " " + scheduleOid); } catch(Exception ex) { log.debug("Setting Rollback Only"); ts.setRollbackOnly(); } return null; } } ); }
Example #13
Source File: TargetDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
/** * Basic save all method. This will save all of the objects in the * collection to the database but will perform nothing more than the * Hibernate save/cascade logic. It should not be used to save a collection * of targets or target groups. * @param collection A collection of objects to be saved. */ public void saveAll(final Collection collection) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { log.debug("Before Saving Object"); for(Object o: collection) { getSession().saveOrUpdate(o); } log.debug("After Saving Object"); } catch(Exception ex) { log.debug("Setting Rollback Only"); ts.setRollbackOnly(); } return null; } } ); }
Example #14
Source File: IndicatorCriteriaDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
public void delete(final Object aObject) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { log.debug("Before Delete of Object"); getHibernateTemplate().delete(aObject); log.debug("After Deletes Object"); } catch (DataAccessException e) { log.warn("Setting Rollback Only",e); ts.setRollbackOnly(); throw e; } return null; } } ); }
Example #15
Source File: InTrayDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
public void deleteNotificationsByUser(final Long userOid) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { log.debug("Before Deleting all Notifications"); String hqlDelete = "delete Notification n where n.recipientOid = :recipientOid"; int deletedEntities = getSession().createQuery( hqlDelete ) .setLong( "recipientOid", userOid ) .executeUpdate(); //getHibernateTemplate().delete(obj); log.debug("After Deleting "+deletedEntities+" Notifications"); } catch (DataAccessException e) { log.warn("Setting Rollback Only",e); ts.setRollbackOnly(); throw e; } return null; } } ); }
Example #16
Source File: PipelineService.java From gocd with Apache License 2.0 | 6 votes |
public Pipeline save(final Pipeline pipeline) { String mutexPipelineName = PipelinePauseService.mutexForPausePipeline(pipeline.getName()); synchronized (mutexPipelineName) { return (Pipeline) transactionTemplate.execute((TransactionCallback) status -> { if (pipeline instanceof NullPipeline) { return pipeline; } updateCounter(pipeline); Pipeline pipelineWithId = pipelineDao.save(pipeline); pipelineLockService.lockIfNeeded(pipelineWithId); for (Stage stage : pipeline.getStages()) { stageService.save(pipelineWithId, stage); } pipelineTimeline.update(); return pipelineWithId; }); } }
Example #17
Source File: PatchForUpdatingPolicyJson_J10019.java From ranger with Apache License 2.0 | 6 votes |
@Override public void run() { errorMsg = txTemplate.execute(new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { String ret = null; try { policyRefUpdater.cleanupRefTables(policy); portPolicy(service.getType(), policy); } catch (Throwable e) { logger.error("PortPolicy failed for policy:[" + policy + "]", e); ret = e.toString(); } return ret; } }); }
Example #18
Source File: JdoTransactionManagerTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testTransactionCommitWithPropagationSupports() { given(pmf.getPersistenceManager()).willReturn(pm); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); final List l = new ArrayList(); l.add("test"); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Is not new transaction", !status.isNewTransaction()); PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true); return l; } }); assertTrue("Correct result list", result == l); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); verify(pm, times(2)).close(); }
Example #19
Source File: WebSphereUowTransactionManagerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void propagationMandatoryFailsInCaseOfNoExistingTransaction() { MockUOWManager manager = new MockUOWManager(); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_MANDATORY); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown IllegalTransactionStateException"); } catch (IllegalTransactionStateException ex) { // expected } }
Example #20
Source File: CompanySchedulerTest.java From vladmihalcea.wordpress.com with Apache License 2.0 | 6 votes |
@Test public void test() throws InterruptedException { transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Company tvCompany = new Company(); tvCompany.setName("TV Company"); Company radioCompany = new Company(); radioCompany.setName("Radio Company"); entityManager.persist(tvCompany); entityManager.persist(radioCompany); return null; } }); Thread.sleep(500); }
Example #21
Source File: HandlingModeJtaConnectionReleaseTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
@Test @Ignore public void test() { //Warming up for (int i = 0; i < 100; i++) { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { assertNotNull(entityManager.createNativeQuery("select now()").getSingleResult()); return null; }); } for (int batch : batches) { long startNanos = System.nanoTime(); transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { for (int i = 0; i < batch; i++) { assertNotNull(entityManager.createNativeQuery("select now()").getSingleResult()); } return null; }); LOGGER.info("Transaction took {} millis", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos)); } transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { entityManager.unwrap(Session.class).getSessionFactory().getStatistics().logSummary(); return null; }); }
Example #22
Source File: HarvestCoordinatorDAOImpl.java From webcurator with Apache License 2.0 | 6 votes |
/** @see org.webcurator.domain.HarvestCoordinatorDAO#delete(BandwidthRestriction). */ public void delete(final BandwidthRestriction aBandwidthRestriction) { txTemplate.execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus ts) { try { getSession().delete(aBandwidthRestriction); } catch(Exception ex) { ts.setRollbackOnly(); } return null; } } ); }
Example #23
Source File: WebSphereUowTransactionManagerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void propagationNeverFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NEVER); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown IllegalTransactionStateException"); } catch (IllegalTransactionStateException ex) { // expected } }
Example #24
Source File: WebSphereUowTransactionManagerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void propagationNestedFailsInCaseOfExistingTransaction() { MockUOWManager manager = new MockUOWManager(); manager.setUOWStatus(UOWManager.UOW_STATUS_ACTIVE); WebSphereUowTransactionManager ptm = new WebSphereUowTransactionManager(manager); DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); try { ptm.execute(definition, new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus status) { return "result"; } }); fail("Should have thrown NestedTransactionNotSupportedException"); } catch (NestedTransactionNotSupportedException ex) { // expected } }
Example #25
Source File: HibernateTransactionManagerTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
@Before public void init() { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { Tag hibernate = new Tag(); hibernate.setName("hibernate"); sessionFactory.getCurrentSession().persist(hibernate); Tag jpa = new Tag(); jpa.setName("jpa"); sessionFactory.getCurrentSession().persist(jpa); return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } }
Example #26
Source File: HibernateCriteriaTest.java From vladmihalcea.wordpress.com with Apache License 2.0 | 6 votes |
private Product getProduct_Gracefully() { return transactionTemplate.execute(new TransactionCallback<Product>() { @Override public Product doInTransaction(TransactionStatus transactionStatus) { return entityManager.createQuery( "select p " + "from Product p " + "inner join p.warehouseProductInfo w " + "where " + " p.code = :code and " + " w.quantity > :quantity ", Product.class) .setParameter("code", "tvCode") .setParameter("quantity", 50) .getSingleResult(); } }); }
Example #27
Source File: PersistenceContextTransactionTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testTransactionCommitWithSharedEntityManager() { given(manager.getTransaction()).willReturn(tx); tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { bean.sharedEntityManager.flush(); return null; } }); verify(tx).commit(); verify(manager).flush(); verify(manager).close(); }
Example #28
Source File: SpringJpaXmlTest.java From hypersistence-optimizer with Apache License 2.0 | 6 votes |
@Before public void init() { try { transactionTemplate.execute((TransactionCallback<Void>) transactionStatus -> { Tag hibernate = new Tag(); hibernate.setName("hibernate"); entityManager.persist(hibernate); Tag jpa = new Tag(); jpa.setName("jpa"); entityManager.persist(jpa); return null; }); } catch (TransactionException e) { LOGGER.error("Failure", e); } }
Example #29
Source File: JdoTransactionManagerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testTransactionRollbackWithAlreadyRolledBack() { given(pmf.getPersistenceManager()).willReturn(pm); given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); try { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf)); PersistenceManagerFactoryUtils.getPersistenceManager(pmf, true); throw new RuntimeException("application exception"); } }); fail("Should have thrown RuntimeException"); } catch (RuntimeException ex) { // expected } assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); verify(pm).close(); verify(tx).begin(); }
Example #30
Source File: JpaTransactionManagerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testTransactionRollbackWithPreboundAndPropagationSupports() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); try { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { assertTrue(TransactionSynchronizationManager.hasResource(factory)); assertTrue(TransactionSynchronizationManager.isSynchronizationActive()); assertTrue(!status.isNewTransaction()); EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush(); status.setRollbackOnly(); return null; } }); assertTrue(TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); } finally { TransactionSynchronizationManager.unbindResource(factory); } verify(manager).flush(); verify(manager).clear(); }