List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.jspresso.hrsample.backend.ApplicationSessionTest.java
/** * Tests that uninitialized reference property are correctly loaded and registered to the session * when actually loaded. see bug #1150./*from w w w . ja va 2 s. c o m*/ */ @Test public void testUninitializedPropertyRegisteredWhenLoaded() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); OrganizationalUnit ou = hbc.getTransactionTemplate().execute(new TransactionCallback<OrganizationalUnit>() { @Override public OrganizationalUnit doInTransaction(TransactionStatus status) { EnhancedDetachedCriteria employeeCriteria = EnhancedDetachedCriteria.forClass(Employee.class); List<Employee> employees = hbc.findByCriteria(employeeCriteria, null, Employee.class); for (Employee emp : employees) { OrganizationalUnit managedOu = (OrganizationalUnit) emp .straightGetProperty(Employee.MANAGED_OU); if (!Hibernate.isInitialized(managedOu)) { EnhancedDetachedCriteria companyCriteria = EnhancedDetachedCriteria.forClass(Company.class); Company company = hbc.findFirstByCriteria(companyCriteria, EMergeMode.MERGE_KEEP, Company.class); emp = hbc.merge(emp, EMergeMode.MERGE_LAZY); for (Department department : company.getDepartments()) { for (Team team : department.getTeams()) { team.getName(); } } // Will initialize return emp.getManagedOu(); } } return null; } }); if (ou != null) { assertTrue("Loaded lazy reference has not correctly been merged to the application session", HibernateHelper.objectEquals(ou, hbc.getRegisteredEntity(OrganizationalUnit.class, ou.getId()))); } }
From source file:hhh5855.HHH5855ListChildrenDuplicatesTest.java
/** * This test will work fine. We persist the children first, then call merge on * the parent//from ww w .ja va 2 s . c om */ @Test public void testFixByPersistingChild() { 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"); Child child2 = new Child(); child2.setName("child2"); entityManager.persist(child1); entityManager.persist(child2); parent.addChild(child1); parent.addChild(child2); entityManager.merge(parent); parent.getChildren().size(); return parent; } }); assertEquals(2, parent.getChildren().size()); }
From source file:org.openremote.beehive.configuration.www.CommandsAPI.java
@POST public Response createCommand(final CommandDTOIn commandDTO) { if (device.getCommandByName(commandDTO.getName()) != null) { return javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.CONFLICT) .entity(new ErrorDTO(409, "A command with the same name already exists")).build(); }//from ww w.ja v a 2s .c o m return Response.ok(new CommandDTOOut( new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Command>() { @Override public Command doInTransaction(TransactionStatus transactionStatus) { Command newCommand = new Command(); populateCommandFromDTO(newCommand, commandDTO); commandRepository.save(newCommand); return newCommand; } }))).build(); }
From source file:com.khs.test.jdbc.datasource.DSInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;// www . j a v a2s. c om TransactionTemplate transactionTemplate = new TransactionTemplate( new DataSourceTransactionManager(dataSource)); transactionTemplate.execute(new TransactionCallback() { @SuppressWarnings("unchecked") public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String[] scripts; try { scripts = StringUtils.delimitedListToStringArray( stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";"); } catch (IOException e) { throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); } for (int i = 0; i < scripts.length; i++) { String script = scripts[i].trim(); if (StringUtils.hasText(script)) { try { jdbcTemplate.execute(script); } catch (DataAccessException e) { if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) { logger.debug("DROP script failed (ignoring): " + script); } else { throw e; } } } } return null; } }); }
From source file:springbatch.test.jdbc.datasource.DataSourceInitializer.java
private void doExecuteScript(final Resource scriptResource) { if (scriptResource == null || !scriptResource.exists()) return;/* ww w . j a va2 s . c o m*/ TransactionTemplate transactionTemplate = new TransactionTemplate( new DataSourceTransactionManager(dataSource)); transactionTemplate.execute(new TransactionCallback() { @SuppressWarnings("unchecked") public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String[] scripts; try { scripts = StringUtils.delimitedListToStringArray( stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";"); } catch (IOException e) { throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e); } for (int i = 0; i < scripts.length; i++) { String script = scripts[i].trim(); if (StringUtils.hasText(script)) { try { jdbcTemplate.execute(scripts[i]); } catch (DataAccessException e) { if (!script.toUpperCase().startsWith("DROP")) { throw e; } } } } return null; } }); }
From source file:com.vladmihalcea.util.DatabaseScriptLifecycleHandler.java
public void initDatabase() { if (transactional) { transactionTemplate.execute(new TransactionCallback<Void>() { @Override//w w w.j a va2 s . c o m public Void doInTransaction(TransactionStatus status) { runInitScripts(); return null; } }); } else { runInitScripts(); } }
From source file:org.cleverbus.core.common.asynch.repair.RepairExternalCallDbImplTest.java
private ExternalCall[] createAndSaveExternalCalls(final int quantity) { TransactionTemplate tx = new TransactionTemplate(jpaTransactionManager); return tx.execute(new TransactionCallback<ExternalCall[]>() { @Override/*from w ww. j a v a2s . c o m*/ public ExternalCall[] doInTransaction(TransactionStatus status) { ExternalCall[] extCalls = new ExternalCall[quantity]; for (int i = 0; i < extCalls.length; i++) { Message message = createMessage(ExternalSystemTestEnum.CRM, ServiceTestEnum.CUSTOMER, "someOperation", "some payload"); extCalls[i] = ExternalCall.createProcessingCall("direct:someOperation", UUID.randomUUID().toString(), message); extCalls[i].setLastUpdateTimestamp(DateTime.now().minusHours(1).toDate()); em.persist(message); em.persist(extCalls[i]); } em.flush(); return extCalls; } }); }
From source file:org.axonframework.migration.eventstore.JpaEventStoreMigrator.java
public boolean run() throws Exception { final AtomicInteger updateCount = new AtomicInteger(); final AtomicInteger skipCount = new AtomicInteger(); final AtomicLong lastId = new AtomicLong( Long.parseLong(configuration.getProperty("lastProcessedId", "-1"))); try {/*from w ww. ja va 2 s . com*/ TransactionTemplate template = new TransactionTemplate(txManager); template.setReadOnly(true); System.out.println("Starting conversion. Fetching batches of " + QUERY_BATCH_SIZE + " items."); while (template.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { final Session hibernate = entityManager.unwrap(Session.class); Iterator<Object[]> results = hibernate.createQuery( "SELECT e.aggregateIdentifier, e.sequenceNumber, e.type, e.id FROM DomainEventEntry e " + "WHERE e.id > :lastIdentifier ORDER BY e.id ASC") .setFetchSize(1000).setMaxResults(QUERY_BATCH_SIZE).setReadOnly(true) .setParameter("lastIdentifier", lastId.get()).iterate(); if (!results.hasNext()) { System.out.println("Empty batch. Assuming we're done."); return false; } else if (Thread.interrupted()) { System.out.println("Received an interrupt. Stopping..."); return false; } while (results.hasNext()) { List<ConversionItem> conversionBatch = new ArrayList<ConversionItem>(); while (conversionBatch.size() < CONVERSION_BATCH_SIZE && results.hasNext()) { Object[] item = results.next(); String aggregateIdentifier = (String) item[0]; long sequenceNumber = (Long) item[1]; String type = (String) item[2]; Long entryId = (Long) item[3]; lastId.set(entryId); conversionBatch .add(new ConversionItem(sequenceNumber, aggregateIdentifier, type, entryId)); } if (!conversionBatch.isEmpty()) { executor.submit(new TransformationTask(conversionBatch, skipCount)); } } return true; } })) { System.out.println("Reading next batch, starting at ID " + lastId.get() + "."); System.out.println( "Estimated backlog size is currently: " + (workQueue.size() * CONVERSION_BATCH_SIZE)); } } finally { executor.shutdown(); executor.awaitTermination(5, TimeUnit.MINUTES); if (lastId.get() >= 0) { System.out.println( "Processed events from old event store up to (and including) id = " + lastId.get()); } } System.out.println("In total " + updateCount.get() + " items have been converted."); return skipCount.get() == 0; }
From source file:net.solarnetwork.node.dao.jdbc.AbstractBatchableJdbcDao.java
@Override public BatchResult batchProcess(final BatchCallback<T> callback, final BatchOptions options) { if (transactionTemplate != null) { return transactionTemplate.execute(new TransactionCallback<BatchResult>() { @Override/*w w w .j av a2s . c o m*/ public net.solarnetwork.node.dao.BatchableDao.BatchResult doInTransaction( TransactionStatus status) { return batchProcessInternal(callback, options); } }); } else { return batchProcessInternal(callback, options); } }
From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirSystemDao.java
private int doPerformReindexingPassForResources(final Integer theCount, TransactionTemplate txTemplate) { return txTemplate.execute(new TransactionCallback<Integer>() { @SuppressWarnings("unchecked") @Override/*from w ww .j a v a 2 s.c o m*/ public Integer doInTransaction(TransactionStatus theStatus) { TypedQuery<ResourceTable> q = myEntityManager.createQuery( "SELECT t FROM " + ResourceTable.class.getSimpleName() + " t WHERE t.myIndexStatus IS null", ResourceTable.class); int maxResult = 500; if (theCount != null) { maxResult = Math.min(theCount, 2000); } q.setMaxResults(maxResult); List<ResourceTable> resources = q.getResultList(); if (resources.isEmpty()) { return 0; } ourLog.info("Indexing {} resources", resources.size()); int count = 0; long start = System.currentTimeMillis(); for (ResourceTable resourceTable : resources) { try { /* * This part is because from HAPI 1.5 - 1.6 we changed the format of forced ID to be "type/id" instead of just "id" */ ForcedId forcedId = resourceTable.getForcedId(); if (forcedId != null) { if (isBlank(forcedId.getResourceType())) { ourLog.info("Updating resource {} forcedId type to {}", forcedId.getForcedId(), resourceTable.getResourceType()); forcedId.setResourceType(resourceTable.getResourceType()); myForcedIdDao.save(forcedId); } } final IBaseResource resource = toResource(resourceTable, false); @SuppressWarnings("rawtypes") final IFhirResourceDao dao = getDao(resource.getClass()); dao.reindex(resource, resourceTable); } catch (Exception e) { ourLog.error("Failed to index resource {}: {}", new Object[] { resourceTable.getIdDt(), e.toString(), e }); throw new ReindexFailureException(resourceTable.getId()); } count++; } long delay = System.currentTimeMillis() - start; long avg = (delay / resources.size()); ourLog.info("Indexed {} / {} resources in {}ms - Avg {}ms / resource", new Object[] { count, resources.size(), delay, avg }); return resources.size(); } }); }