Java Code Examples for org.springframework.transaction.support.TransactionCallback

The following examples show how to use org.springframework.transaction.support.TransactionCallback. These examples are extracted from open source projects. 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
@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 2
@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 3
@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 Project: azeroth   Source File: MybatisTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
@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 6
Source Project: gocd   Source File: StageSqlMapDao.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: hypersistence-optimizer   Source File: SpringJpaTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: ranger   Source File: PatchForUpdatingTagsJson_J10020.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
@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 10
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 11
Source Project: webcurator   Source File: TargetInstanceDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 12
Source Project: hypersistence-optimizer   Source File: SpringJpaXmlTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
Source Project: webcurator   Source File: TargetDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 Project: webcurator   Source File: IndicatorCriteriaDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: webcurator   Source File: InTrayDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: gocd   Source File: PipelineService.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: ranger   Source File: PatchForUpdatingPolicyJson_J10019.java    License: Apache License 2.0 6 votes vote down vote up
@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
@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
@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
@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
@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 Project: webcurator   Source File: HarvestCoordinatorDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** @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
@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
@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
@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
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
@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 Project: webcurator   Source File: TargetInstanceDAOImpl.java    License: Apache License 2.0 6 votes vote down vote up
/** @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 29
Source Project: spring-analysis-note   Source File: JpaTransactionManagerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testTransactionCommit() {
	given(manager.getTransaction()).willReturn(tx);

	final List<String> l = new ArrayList<>();
	l.add("test");

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	Object result = tt.execute(new TransactionCallback() {
		@Override
		public Object doInTransaction(TransactionStatus status) {
			assertTrue(TransactionSynchronizationManager.hasResource(factory));
			EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
			return l;
		}
	});
	assertSame(l, result);

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(tx).commit();
	verify(manager).flush();
	verify(manager).close();
}
 
Example 30
Source Project: olat   Source File: UpdateEventsITCaseNew.java    License: Apache License 2.0 5 votes vote down vote up
private List<Subscriber> generateSubscribers() {
    return new TransactionTemplate(transactionManager).execute(new TransactionCallback<List<Subscriber>>() {
        public List<Subscriber> doInTransaction(TransactionStatus status) {
            return notificationTestDataGenerator.generateSubscribers(NUMBER_OF_SUBSCRIBERS);
        }
    });
}