List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:dk.nsi.sdm4.ydelse.parser.YdelseInserter.java
private void commitBatch() { transactionTemplate.execute(new TransactionCallback<Void>() { @Override/*from w w w . ja v a2 s . c o m*/ public Void doInTransaction(TransactionStatus status) { if (batch.size() > 0) { log.info("Committing batch of size " + batch.size()); for (SsrAction ssrAction : batch) { ssrAction.execute(dao); } batch.clear(); } return null; // kun for at gre TransactionCallback-interfacet glad, ingen bruger en returvrdi til noget } }); }
From source file:com.javaetmoi.core.persistence.hibernate.TestIssue3.java
@Test public void listWithMappedEntityWithAdditionalSpecificCriteria() { List<System> dbContainer = transactionTemplate.execute(new TransactionCallback<List<System>>() { public List<System> doInTransaction(TransactionStatus status) { List<System> system = (List<System>) sessionFactory.getCurrentSession().createCriteria(System.class) .addOrder(Order.asc("systemNumber")).list(); LazyLoadingUtil.deepHydrate(sessionFactory.getCurrentSession(), system); return system; }/*from ww w. j a v a 2 s .c om*/ }); assertNotNull(dbContainer); assertFalse(dbContainer.isEmpty()); assertEquals(2, dbContainer.size()); assertEquals(new Integer(1), dbContainer.get(0).getId()); assertNotNull(dbContainer.get(0).getSubSystems()); assertEquals(2, dbContainer.get(0).getSubSystems().size()); }
From source file:org.openremote.beehive.configuration.www.ControllerConfigurationsAPI.java
@POST public Response createControllerConfiguration(final ControllerConfigurationDTOIn configurationDTO) { if (account.getControllerConfigurationByName(configurationDTO.getName()) != null) { return Response.status(Response.Status.CONFLICT) .entity(new ErrorDTO(409, "A controller configuration with the same name already exists")) .build();/*from ww w.j a v a2 s .c o m*/ } return Response.ok(new ControllerConfigurationDTOOut(new TransactionTemplate(platformTransactionManager) .execute(new TransactionCallback<ControllerConfiguration>() { @Override public ControllerConfiguration doInTransaction(TransactionStatus transactionStatus) { ControllerConfiguration newConfiguration = new ControllerConfiguration(); newConfiguration.setCategory(configurationDTO.getCategory()); newConfiguration.setName(configurationDTO.getName()); newConfiguration.setValue(configurationDTO.getValue()); account.addControllerConfiguration(newConfiguration); controllerConfigurationRepository.save(newConfiguration); return newConfiguration; } }))).build(); }
From source file:com.expedia.seiso.domain.service.impl.ItemServiceImpl.java
/** * Using {@link Propagation.NEVER} because we don't want a single error to wreck the entire operation. *//*from w ww .ja v a 2 s . c o m*/ @Override @Transactional(propagation = Propagation.NEVER) public SaveAllResponse saveAll(@NonNull Class itemClass, @NonNull List<? extends Item> items, boolean mergeAssociations) { val numItems = items.size(); val itemClassName = itemClass.getSimpleName(); log.info("Batch saving {} items ({})", numItems, itemClass.getSimpleName()); val errors = new ArrayList<SaveAllError>(); for (val item : items) { try { // Have to doInTransaction() since calling save() happens behind the transactional proxy. // Also, see http://stackoverflow.com/questions/5568409/java-generics-void-void-types txTemplate.execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(TransactionStatus status) { save(item, mergeAssociations); return null; } }); } catch (RuntimeException e) { e.printStackTrace(); val message = e.getClass() + ": " + e.getMessage(); errors.add(new SaveAllError(item.itemKey(), message)); } } val numErrors = errors.size(); if (numErrors == 0) { log.info("Batch saved {} items ({}) with no errors", numItems, itemClassName); } else { log.warn("Batch saved {} items ({}) with {} errors: {}", numItems, itemClassName, numErrors, errors); } return new SaveAllResponse(numItems, numErrors, errors); }
From source file:org.cleverbus.core.common.asynch.queue.MessagesPoolDbImpl.java
private boolean lockMessage(final Message msg) { Assert.notNull(msg, "the msg must not be null"); boolean isLock; try {/*from w w w.j ava2 s .c o m*/ isLock = transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(final TransactionStatus transactionStatus) { return messageDao.updateMessageForLock(msg); } }); } catch (DataAccessException ex) { isLock = false; } if (isLock) { Log.debug("Successfully locked message for re-processing: {}", msg.toHumanString()); return true; } else { Log.debug("Failed to lock message for re-processing: {}", msg.getMsgId()); return false; } }
From source file:com.github.ferstl.spring.jdbc.oracle.DatabaseConfiguration.java
private void prepareDatabase() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(new ClassPathResource("prepare-database.sql")); populator.setIgnoreFailedDrops(true); TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager()); trxTemplate.execute(new TransactionCallback<Void>() { @Override//from ww w . j ava2s .co m public Void doInTransaction(TransactionStatus status) { DatabasePopulatorUtils.execute(populator, DatabaseConfiguration.this.dataSource); return null; } }); }
From source file:com.vladmihalcea.HibernateLinkedSetTest.java
protected Long cleanAndSaveParent() { return transactionTemplate.execute(new TransactionCallback<Long>() { @Override/*from www .ja v a2s. c o m*/ public Long doInTransaction(TransactionStatus transactionStatus) { entityManager.createQuery("delete from LinkedChild where id > 0").executeUpdate(); entityManager.createQuery("delete from LinkedParent where id > 0").executeUpdate(); assertTrue(entityManager.createQuery("from LinkedParent").getResultList().isEmpty()); LinkedParent parent = new LinkedParent(); entityManager.persist(parent); entityManager.flush(); return parent.getId(); } }); }
From source file:org.openremote.beehive.configuration.www.SensorsAPI.java
@POST public Response createSensor(final SensorDTOIn sensorDTO) { if (device.getSensorByName(sensorDTO.getName()) != null) { return Response.status(Response.Status.CONFLICT) .entity(new ErrorDTO(409, "A sensor with the same name already exists")).build(); }/* w ww .ja v a2 s .c o m*/ try { Command command = device.getCommandById(sensorDTO.getCommandId()); } catch (NotFoundException e) { return Response.status(Response.Status.BAD_REQUEST) .entity(new ErrorDTO(400, "Referenced command does not exist")).build(); } return Response.ok(new SensorDTOOut( new TransactionTemplate(platformTransactionManager).execute(new TransactionCallback<Sensor>() { @Override public Sensor doInTransaction(TransactionStatus transactionStatus) { Sensor newSensor = createSensorFromDTO(sensorDTO); sensorRepository.save(newSensor); return newSensor; } }))).build(); }
From source file:org.motechproject.server.omod.sdsched.TxSyncManWrapperImplTest.java
public void testBindResource() { final String resourceName = "A Resource"; final String resourceValue = "A Resource value"; Object retVal = txTempl.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { txSyncManWrapper.bindResource(resourceName, resourceValue); return TransactionSynchronizationManager.getResource(resourceName); } finally { TransactionSynchronizationManager.unbindResourceIfPossible(resourceName); }// w w w.ja v a 2 s . c om } }); assertEquals(resourceValue, retVal); }
From source file:com.alibaba.otter.node.etl.common.db.DbPerfIntergration.java
@Test public void test_stack() { DbMediaSource dbMediaSource = new DbMediaSource(); dbMediaSource.setId(1L);//from www . jav a 2s. c om dbMediaSource.setDriver("com.mysql.jdbc.Driver"); dbMediaSource.setUsername("otter"); dbMediaSource.setPassword("otter"); dbMediaSource.setUrl("jdbc:mysql://127.0.0.1:3306/retl"); dbMediaSource.setEncode("UTF-8"); dbMediaSource.setType(DataMediaType.MYSQL); DbDataMedia dataMedia = new DbDataMedia(); dataMedia.setSource(dbMediaSource); dataMedia.setId(1L); dataMedia.setName("ljhtable1"); dataMedia.setNamespace("otter"); final DbDialect dbDialect = dbDialectFactory.getDbDialect(2L, dataMedia.getSource()); want.object(dbDialect).clazIs(MysqlDialect.class); final TransactionTemplate transactionTemplate = dbDialect.getTransactionTemplate(); // ?? int minute = 5; int nextId = 1; final int thread = 10; final int batch = 50; final String sql = "insert into otter.ljhtable1 values(? , ? , ? , ?)"; final CountDownLatch latch = new CountDownLatch(thread); ExecutorService executor = new ThreadPoolExecutor(thread, thread, 60, TimeUnit.SECONDS, new ArrayBlockingQueue(thread * 2), new NamedThreadFactory("load"), new ThreadPoolExecutor.CallerRunsPolicy()); for (int sec = 0; sec < minute * 60; sec++) { // long startTime = System.currentTimeMillis(); for (int i = 0; i < thread; i++) { final int start = nextId + i * batch; executor.submit(new Runnable() { public void run() { try { transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { JdbcTemplate jdbcTemplate = dbDialect.getJdbcTemplate(); return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int idx) throws SQLException { int id = start + idx; StatementCreatorUtils.setParameterValue(ps, 1, Types.INTEGER, null, id); StatementCreatorUtils.setParameterValue(ps, 2, Types.VARCHAR, null, RandomStringUtils.randomAlphabetic(1000)); // RandomStringUtils.randomAlphabetic() long time = new Date().getTime(); StatementCreatorUtils.setParameterValue(ps, 3, Types.TIMESTAMP, new Timestamp(time)); StatementCreatorUtils.setParameterValue(ps, 4, Types.TIMESTAMP, new Timestamp(time)); } public int getBatchSize() { return batch; } }); } }); } finally { latch.countDown(); } } }); } long endTime = System.currentTimeMillis(); try { latch.await(1000 * 60L - (endTime - startTime), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } if (latch.getCount() != 0) { System.out.println("perf is not enough!"); System.exit(-1); } endTime = System.currentTimeMillis(); System.out.println("Time cost : " + (System.currentTimeMillis() - startTime)); try { TimeUnit.MILLISECONDS.sleep(1000L - (endTime - startTime)); } catch (InterruptedException e) { e.printStackTrace(); } nextId = nextId + thread * batch; } executor.shutdown(); }