List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:cherry.sqlapp.service.sqltool.exec.ExecLoadFileProcessHandler.java
@Override public FileProcessResult handleFile(final File file, String name, String originalFilename, String contentType, long size, long asyncId, String... args) throws IOException { final DataSource dataSource = dataSourceDef.getDataSource(args[0]); final String sql = args[1]; TransactionOperations txOp = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); return txOp.execute(new TransactionCallback<FileProcessResult>() { @Override//from w w w . j a v a 2 s .c om public FileProcessResult doInTransaction(TransactionStatus status) { try (InputStream in = new FileInputStream(file); Reader reader = new InputStreamReader(in, charset)) { LoadResult r = loader.load(dataSource, sql, new CsvProvider(reader, true), new NoneLimiter()); FileProcessResult result = new FileProcessResult(); result.setTotalCount(r.getTotalCount()); result.setOkCount(r.getSuccessCount()); result.setNgCount(r.getFailedCount()); return result; } catch (IOException ex) { throw new IllegalStateException(ex); } } }); }
From source file:com.vladmihalcea.HibernateListMultiLevelFetchTest.java
@Test public void test() { final Long forestId = transactionTemplate.execute(new TransactionCallback<Long>() { @Override//from www . j av a 2 s. com public Long doInTransaction(TransactionStatus transactionStatus) { Forest forest = new Forest(); Tree tree1 = new Tree(); tree1.setIndex(0); Branch branch11 = new Branch(); branch11.setIndex(0); Leaf leaf111 = new Leaf(); leaf111.setIndex(0); Leaf leaf112 = new Leaf(); leaf111.setIndex(1); Leaf leaf113 = new Leaf(); leaf111.setIndex(2); Leaf leaf114 = new Leaf(); leaf111.setIndex(3); branch11.addLeaf(leaf111); branch11.addLeaf(leaf112); branch11.addLeaf(leaf113); branch11.addLeaf(leaf114); Branch branch12 = new Branch(); branch12.setIndex(1); Leaf leaf121 = new Leaf(); leaf121.setIndex(1); Leaf leaf122 = new Leaf(); leaf122.setIndex(2); Leaf leaf123 = new Leaf(); leaf123.setIndex(3); Leaf leaf124 = new Leaf(); leaf124.setIndex(4); branch12.addLeaf(leaf121); branch12.addLeaf(leaf122); branch12.addLeaf(leaf123); branch12.addLeaf(leaf124); tree1.addBranch(branch11); tree1.addBranch(branch12); Tree tree2 = new Tree(); tree2.setIndex(1); Branch branch21 = new Branch(); branch21.setIndex(0); Leaf leaf211 = new Leaf(); leaf211.setIndex(0); Leaf leaf212 = new Leaf(); leaf111.setIndex(1); Leaf leaf213 = new Leaf(); leaf111.setIndex(2); Leaf leaf214 = new Leaf(); leaf111.setIndex(3); branch21.addLeaf(leaf211); branch21.addLeaf(leaf212); branch21.addLeaf(leaf213); branch21.addLeaf(leaf214); Branch branch22 = new Branch(); branch22.setIndex(2); Leaf leaf221 = new Leaf(); leaf121.setIndex(0); Leaf leaf222 = new Leaf(); leaf121.setIndex(1); Leaf leaf223 = new Leaf(); leaf121.setIndex(2); branch22.addLeaf(leaf221); branch22.addLeaf(leaf222); branch22.addLeaf(leaf223); tree2.addBranch(branch21); tree2.addBranch(branch22); forest.addTree(tree1); forest.addTree(tree2); entityManager.persist(forest); entityManager.flush(); return forest.getId(); } }); Forest forest = transactionTemplate.execute(new TransactionCallback<Forest>() { @Override public Forest doInTransaction(TransactionStatus transactionStatus) { return entityManager.find(Forest.class, forestId); } }); try { navigateForest(forest); fail("Should have thrown LazyInitializationException!"); } catch (LazyInitializationException expected) { } forest = transactionTemplate.execute(new TransactionCallback<Forest>() { @Override public Forest doInTransaction(TransactionStatus transactionStatus) { Forest f = entityManager .createQuery("select f " + "from Forest f " + "join fetch f.trees t " + "join fetch t.branches b " + "join fetch b.leaves l ", Forest.class) .getSingleResult(); return f; } }); navigateForest(forest); }
From source file:com.opensymphony.able.service.CrudServiceAndActionTest.java
@Test(dataProvider = "spring") public void testCrudServices(String classpathUri) throws Exception { ApplicationContext context = loadContext(classpathUri); final PersonService service = new PersonService(); SpringHelper.injectBeans(service, context); TransactionTemplate transactionTemplate = (TransactionTemplate) getMandatoryBean(context, "transactionTemplate"); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { Person user = new Person(); user.setUsername("james"); user.setFirstName("James"); service.getJpaTemplate().persist(user); return null; }/*from w w w. j a va2s .c om*/ }); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus transactionStatus) { try { testNativeSql(service); } catch (Exception e) { System.out.println("Caught: " + e); e.printStackTrace(System.out); System.out.println("done"); throw new RuntimeException(e); } return null; } }); // TODO can't seem to get this to work... //testBinding(service); }
From source file:org.okj.commons.service.action.SimpleActionsExecutor.java
/** * action/* w w w . j ava2 s .co m*/ * * @param context */ protected void doExecuteWithTransaction(final Actions actions, final ActionContext context) { transactionTemplate.execute(new TransactionCallback() { /** * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus) */ @Override public Object doInTransaction(TransactionStatus status) { try { doExecuteWithoutTransaction(actions, context); } catch (ActionException ex) { context.occurError(ex); // status.setRollbackOnly(); // } catch (Exception ex) { LogUtils.error(LOGGER, "action", ex); context.occurError(new ActionException(ActionErrorCode.SYSTEM_ERROR_CODE)); // status.setRollbackOnly(); // } return null; } }); // rethrowExcetpion(context); }
From source file:hhh5855.HHH5855ListChildrenDuplicatesTest.java
/** * This test fails. We add two unsaved children to a loaded parent, then we * merge the parent. Hibernate saves 4 rows instead of two. *//*from ww w. java 2s .c o m*/ @Test public void test() { final Long parentId = cleanAndSaveParent(); Parent parent = transactionTemplate.execute(new TransactionCallback<Parent>() { @Override public Parent doInTransaction(TransactionStatus transactionStatus) { Parent parent = loadParent(parentId); Child child1 = new Child(); child1.setName("child1"); child1.setParent(parent); Child child2 = new Child(); child2.setName("child2"); child2.setParent(parent); parent.addChild(child1); parent.addChild(child2); entityManager.merge(parent); entityManager.flush(); if (parent.getChildren().size() == 4) { LOG.error("!!! DUPLICATE ROWS GENERATED !!!"); } return parent; } }); assertEquals(2, parent.getChildren().size()); }
From source file:com.vladmihalcea.HibernateEqualsHashCodeTest.java
@Test public void testRootObjects() { final Company newCompany = new Company(); newCompany.setName("TV Company"); final Long companyId = transactionTemplate.execute(new TransactionCallback<Long>() { @Override//ww w . j a v a2s .co m public Long doInTransaction(TransactionStatus transactionStatus) { entityManager.persist(newCompany); return newCompany.getId(); } }); Company detachedCompany = transactionTemplate.execute(new TransactionCallback<Company>() { @Override public Company doInTransaction(TransactionStatus transactionStatus) { Company attachedCompany = entityManager.find(Company.class, companyId); assertEquals(newCompany, attachedCompany); assertEquals(newCompany.hashCode(), attachedCompany.hashCode()); return attachedCompany; } }); assertEquals(newCompany, detachedCompany); assertEquals(newCompany.hashCode(), detachedCompany.hashCode()); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Company attachedCompany = entityManager.find(Company.class, companyId); attachedCompany.setName("New Company"); entityManager.flush(); return null; } }); transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Company attachedCompany = entityManager.find(Company.class, companyId); assertEquals(newCompany, attachedCompany); assertEquals(newCompany.hashCode(), attachedCompany.hashCode()); return null; } }); }
From source file:net.chrisrichardson.bankingExample.spring.MoneyTransferServiceIntegrationTests.java
public void testTransfer() throws Exception { double fromAccountInitialBalance = 10; double toAccountInitialBalance = 20; final Account fromAccount = AccountMother.makeAccountWithNoOverdraft(fromAccountInitialBalance); final Account toAccount = AccountMother.makeAccountWithNoOverdraft(toAccountInitialBalance); String fromAccountId = fromAccount.getAccountId(); String toAccountId = toAccount.getAccountId(); transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { repository.addAccount(fromAccount); repository.addAccount(toAccount); return null; }// w w w . j av a2s.c om }); service.transfer(fromAccountId, toAccountId, 5); assertBalance(fromAccountInitialBalance - 5, fromAccountId); assertBalance(toAccountInitialBalance + 5, toAccountId); }
From source file:com.vladmihalcea.HibernateCriteriaTest.java
@Test public void test() { transactionTemplate.execute(new TransactionCallback<Void>() { @Override/*from w ww . j av a 2 s. co m*/ public Void doInTransaction(TransactionStatus transactionStatus) { Company company = new Company(); company.setName("TV Company"); entityManager.persist(company); Product product1 = new Product("tvCode"); product1.setName("TV"); product1.setCompany(company); Image frontImage1 = new Image(); frontImage1.setName("front image 1"); frontImage1.setIndex(0); Image sideImage1 = new Image(); sideImage1.setName("side image 1"); sideImage1.setIndex(1); product1.addImage(frontImage1); product1.addImage(sideImage1); WarehouseProductInfo warehouseProductInfo1 = new WarehouseProductInfo(); warehouseProductInfo1.setQuantity(101); product1.addWarehouse(warehouseProductInfo1); Product product2 = new Product("tcSetCode"); product2.setName("TV Set"); product2.setCompany(company); Image frontImage2 = new Image(); frontImage2.setName("front image 2"); frontImage2.setIndex(2); Image sideImage2 = new Image(); sideImage2.setName("side image 2"); sideImage2.setIndex(3); product2.addImage(frontImage2); product2.addImage(sideImage2); WarehouseProductInfo warehouseProductInfo2 = new WarehouseProductInfo(); warehouseProductInfo2.setQuantity(55); product2.addWarehouse(warehouseProductInfo2); Product product3 = new Product("cdPlayerCode"); product3.setName("CD Player"); product3.setCompany(company); WarehouseProductInfo warehouseProductInfo3 = new WarehouseProductInfo(); warehouseProductInfo3.setQuantity(11); product3.addWarehouse(warehouseProductInfo3); Product product = entityManager.find(Product.class, 1L); //product.setQuantity(10); entityManager.persist(product1); entityManager.persist(product2); entityManager.persist(product3); return null; } }); assertProducts(getProducts_Mercilessly()); assertProducts(getProducts_Mercifully()); assertProducts(getProducts_Gracefully()); assertNotNull(getProduct_Mercilessly()); assertNotNull(getProduct_Mercifully()); assertNotNull(getProduct_Gracefully()); assertImageProductDTOs(getImageProductDTOs()); assertImageProductDTOs(getImageProductDTOs_JOOQ()); }
From source file:com.vladmihalcea.HibernateOperationsOrderTest.java
@Test public void test() { final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() { @Override/*from w w w. j a v a 2 s .com*/ public Long doInTransaction(TransactionStatus transactionStatus) { Company company = new Company(); company.setName("TV Company"); entityManager.persist(company); Product product = new Product("tvCode"); product.setName("TV"); product.setCompany(company); Image frontImage = new Image(); frontImage.setName("front image"); frontImage.setIndex(0); Image sideImage = new Image(); sideImage.setName("side image"); sideImage.setIndex(1); product.addImage(frontImage); product.addImage(sideImage); WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo(); warehouseProductInfo.setQuantity(101); product.addWarehouse(warehouseProductInfo); entityManager.persist(product); return product.getId(); } }); try { transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Product product = entityManager.find(Product.class, productId); assertEquals(2, product.getImages().size()); Iterator<Image> imageIterator = product.getImages().iterator(); Image frontImage = imageIterator.next(); assertEquals("front image", frontImage.getName()); assertEquals(0, frontImage.getIndex()); Image sideImage = imageIterator.next(); assertEquals("side image", sideImage.getName()); assertEquals(1, sideImage.getIndex()); Image backImage = new Image(); sideImage.setName("back image"); sideImage.setIndex(1); product.removeImage(sideImage); product.addImage(backImage); product.setName("tv set"); entityManager.flush(); return null; } }); fail("Expected ConstraintViolationException"); } catch (PersistenceException expected) { assertEquals(ConstraintViolationException.class, expected.getCause().getClass()); } transactionTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus transactionStatus) { Product product = entityManager.find(Product.class, productId); assertEquals(2, product.getImages().size()); Iterator<Image> imageIterator = product.getImages().iterator(); Image frontImage = imageIterator.next(); assertEquals("front image", frontImage.getName()); Image sideImage = imageIterator.next(); assertEquals("side image", sideImage.getName()); Image backImage = new Image(); backImage.setName("back image"); backImage.setIndex(1); //http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29 product.removeImage(sideImage); entityManager.flush(); product.addImage(backImage); product.setName("tv set"); entityManager.flush(); return null; } }); }
From source file:ar.com.zauber.commons.spring.web.handlers.TransactionAwareHandlerAdapter.java
/** @see HandlerAdapter#handle( * HttpServletRequest, HttpServletResponse, Object) */ public final ModelAndView handle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { final TransactionTemplate transactionTemplate = transactionStrategy.getTransactionTemplate(handler, request);/*from ww w. j a va2 s. c o m*/ return transactionTemplate.execute(new TransactionCallback<ModelAndView>() { public ModelAndView doInTransaction(final TransactionStatus transactionStatus) { // CHECKSTYLE:ALL:OFF try { return target.handle(request, response, handler); } catch (final RuntimeException e) { //rollback & re-throw original exception transactionStatus.setRollbackOnly(); throw e; } catch (final Exception e) { //rollback & wrap original exception transactionStatus.setRollbackOnly(); throw new RuntimeException("Transaction can not be executed", e); } // CHECKSTYLE:ALL:ON } }); }