List of usage examples for org.springframework.transaction.support TransactionTemplate execute
@Override @Nullable public <T> T execute(TransactionCallback<T> action) throws TransactionException
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
/** * Tests the use of nested transactions. *///from w w w .j a va2 s . com @Test public void testNestedTransactions() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final TransactionTemplate tt = hbc.getTransactionTemplate(); Serializable empId = tt.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus status) { TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus nestedStatus) { DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class); Employee emp = hbc.findFirstByCriteria(empCrit, null, Employee.class); emp.setFirstName("Committed"); return emp.getId(); } }); // asserts that UOW is still active after the end of the nested transaction. assertTrue("UOW should still be active since outer TX is ongoing.", hbc.isUnitOfWorkActive()); // forces rollback of outer TX. status.setRollbackOnly(); return id; } }); DetachedCriteria empById = DetachedCriteria.forClass(Employee.class); empById.add(Restrictions.eq(IEntity.ID, empId)); Employee emp = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class); assertTrue("Inner transaction should have been committed", "Committed".equals(emp.getFirstName())); Serializable emp2Id = tt.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus status) { TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); Serializable id = nestedTT.execute(new TransactionCallback<Serializable>() { @Override public Serializable doInTransaction(TransactionStatus nestedStatus) { DetachedCriteria empCrit = DetachedCriteria.forClass(Employee.class); Employee emp2 = hbc.findFirstByCriteria(empCrit, null, Employee.class); emp2.setFirstName("Rollbacked"); return emp2.getId(); } }); // forces rollback of outer TX. status.setRollbackOnly(); return id; } }); DetachedCriteria emp2ById = DetachedCriteria.forClass(Employee.class); emp2ById.add(Restrictions.eq(IEntity.ID, emp2Id)); Employee emp2 = hbc.findFirstByCriteria(empById, EMergeMode.MERGE_CLEAN_EAGER, Employee.class); assertFalse("Inner transaction should have been rollbacked", "Rollbacked".equals(emp2.getFirstName())); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { City newCity = hbc.getEntityFactory().createEntityInstance(City.class); newCity.setName("Test City"); TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); String testZip = nestedTT.execute(new TransactionCallback<String>() { @Override public String doInTransaction(TransactionStatus nestedStatus) { return "12345"; } }); newCity.setZip(testZip); hbc.registerForUpdate(newCity); } }); tt.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { final City randomCity = hbc.findFirstByCriteria(DetachedCriteria.forClass(City.class), EMergeMode.MERGE_KEEP, City.class); TransactionTemplate nestedTT = new ControllerAwareTransactionTemplate(tt.getTransactionManager()); nestedTT.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); nestedTT.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus nestedStatus) { DetachedCriteria cityById = DetachedCriteria.forClass(City.class); cityById.add(Restrictions.eq(IEntity.ID, randomCity.getId())); City innerRandomCity = (City) cityById.getExecutableCriteria(hbc.getHibernateSession()) .uniqueResult(); // If we reach this point without exception, there is no mix between the inner TX and the outer UOW. // See bug #1118 } }); } }); }
From source file:dao.DatasetsDAO.java
public static ObjectNode getPagedDatasets(String urn, Integer page, Integer size, String user) { ObjectNode result = Json.newObject(); Integer userId = UserDAO.getUserIDByUserName(user); javax.sql.DataSource ds = getJdbcTemplate().getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); final Integer id = userId; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { ObjectNode resultNode = Json.newObject(); List<Dataset> pagedDatasets = new ArrayList<Dataset>(); List<Map<String, Object>> rows = null; if (id != null && id > 0) { if (StringUtils.isBlank(urn)) { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_CURRENT_USER, (page - 1) * size, size, id, id); } else { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_URN_CURRENT_USER, urn + "%", (page - 1) * size, size, id, id); }/*from www . ja v a 2 s.com*/ } else { if (StringUtils.isBlank(urn)) { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET, (page - 1) * size, size); } else { rows = getJdbcTemplate().queryForList(SELECT_PAGED_DATASET_BY_URN, urn + "%", (page - 1) * size, size); } } long count = 0; try { if (StringUtils.isBlank(urn)) { count = getJdbcTemplate().queryForObject(GET_PAGED_DATASET_COUNT, Long.class); } else { count = getJdbcTemplate().queryForObject(GET_PAGED_DATASET_COUNT_BY_URN, Long.class, urn + "%"); } } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } for (Map row : rows) { Dataset ds = new Dataset(); Timestamp modified = (Timestamp) row.get(DatasetWithUserRowMapper.DATASET_MODIFIED_TIME_COLUMN); ds.id = (Long) row.get(DatasetWithUserRowMapper.DATASET_ID_COLUMN); ds.name = (String) row.get(DatasetWithUserRowMapper.DATASET_NAME_COLUMN); ds.source = (String) row.get(DatasetWithUserRowMapper.DATASET_SOURCE_COLUMN); ds.urn = (String) row.get(DatasetWithUserRowMapper.DATASET_URN_COLUMN); ds.schema = (String) row.get(DatasetWithUserRowMapper.DATASET_SCHEMA_COLUMN); String strOwner = (String) row.get(DatasetWithUserRowMapper.DATASET_OWNER_ID_COLUMN); String strOwnerName = (String) row.get(DatasetWithUserRowMapper.DATASET_OWNER_NAME_COLUMN); Long sourceModifiedTime = (Long) row .get(DatasetWithUserRowMapper.DATASET_SOURCE_MODIFIED_TIME_COLUMN); String properties = (String) row.get(DatasetWithUserRowMapper.DATASET_PROPERTIES_COLUMN); try { if (StringUtils.isNotBlank(properties)) { ds.properties = Json.parse(properties); } } catch (Exception e) { Logger.error(e.getMessage()); } if (modified != null && sourceModifiedTime != null && sourceModifiedTime > 0) { ds.modified = modified; ds.formatedModified = modified.toString(); } String[] owners = null; if (StringUtils.isNotBlank(strOwner)) { owners = strOwner.split(","); } String[] ownerNames = null; if (StringUtils.isNotBlank(strOwnerName)) { ownerNames = strOwnerName.split(","); } ds.owners = new ArrayList<User>(); if (owners != null && ownerNames != null) { if (owners.length == ownerNames.length) { for (int i = 0; i < owners.length; i++) { User datasetOwner = new User(); datasetOwner.userName = owners[i]; if (datasetOwner.userName.equalsIgnoreCase(user)) { ds.isOwned = true; } if (StringUtils.isBlank(ownerNames[i]) || ownerNames[i].equalsIgnoreCase("*")) { datasetOwner.name = owners[i]; } else { datasetOwner.name = ownerNames[i]; } ds.owners.add(datasetOwner); } } else { Logger.error("getPagedDatasets get wrong owner and names. Dataset ID: " + Long.toString(ds.id) + " Owner: " + owners + " Owner names: " + ownerNames); } } Integer favoriteId = (Integer) row.get(DatasetWithUserRowMapper.FAVORITE_DATASET_ID_COLUMN); Long watchId = (Long) row.get(DatasetWithUserRowMapper.DATASET_WATCH_ID_COLUMN); Long schemaHistoryRecordCount = 0L; try { schemaHistoryRecordCount = getJdbcTemplate().queryForObject(CHECK_SCHEMA_HISTORY, Long.class, ds.id); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } if (StringUtils.isNotBlank(ds.urn)) { if (ds.urn.substring(0, 4).equalsIgnoreCase(DatasetRowMapper.HDFS_PREFIX)) { ds.hdfsBrowserLink = Play.application().configuration().getString(HDFS_BROWSER_URL_KEY) + ds.urn.substring(DatasetRowMapper.HDFS_URN_PREFIX_LEN); } } if (favoriteId != null && favoriteId > 0) { ds.isFavorite = true; } else { ds.isFavorite = false; } if (watchId != null && watchId > 0) { ds.watchId = watchId; ds.isWatched = true; } else { ds.isWatched = false; ds.watchId = 0L; } if (schemaHistoryRecordCount != null && schemaHistoryRecordCount > 0) { ds.hasSchemaHistory = true; } else { ds.hasSchemaHistory = false; } pagedDatasets.add(ds); } resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("datasets", Json.toJson(pagedDatasets)); return resultNode; } }); return result; }
From source file:org.jspresso.hrsample.backend.JspressoUnitOfWorkTest.java
/** * Tests in TX collection element update with // optimistic locking. *//*from w w w.j a v a 2s . c om*/ @Test public void testInTXCollectionElementUpdate() { final HibernateBackendController hbc = (HibernateBackendController) getBackendController(); final AtomicInteger countDown = new AtomicInteger(10); ExecutorService es = Executors.newFixedThreadPool(countDown.get()); List<Future<Set<String>>> futures = new ArrayList<Future<Set<String>>>(); for (int t = countDown.intValue(); t > 0; t--) { futures.add(es.submit(new Callable<Set<String>>() { @Override public Set<String> call() throws Exception { final HibernateBackendController threadHbc = getApplicationContext() .getBean("applicationBackController", HibernateBackendController.class); final TransactionTemplate threadTT = threadHbc.getTransactionTemplate(); threadHbc.start(hbc.getLocale(), hbc.getClientTimeZone()); threadHbc.setApplicationSession(hbc.getApplicationSession()); BackendControllerHolder.setThreadBackendController(threadHbc); return threadTT.execute(new TransactionCallback<Set<String>>() { /** * {@inheritDoc} */ @Override public Set<String> doInTransaction(TransactionStatus status) { DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Set<String> names = new HashSet<String>(); Company c = (Company) compCrit.getExecutableCriteria(threadHbc.getHibernateSession()) .list().iterator().next(); synchronized (countDown) { countDown.decrementAndGet(); // wait for all threads to arrive here so that we are sure they // have all read the same data. try { countDown.wait(); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } if (c.getName().startsWith("TX_")) { throw new BackendException("Wrong data read from DB"); } c.setName("TX_" + Long.toHexString(System.currentTimeMillis())); names.add(c.getName()); for (Department d : c.getDepartments()) { d.setName(Long.toHexString(System.currentTimeMillis())); names.add(d.getName()); } return names; } }); } })); } while (countDown.get() > 0) { try { Thread.sleep(200); } catch (InterruptedException ex) { throw new BackendException("Test has been interrupted"); } } synchronized (countDown) { countDown.notifyAll(); } int successfullTxCount = 0; Set<String> names = new HashSet<String>(); for (Future<Set<String>> f : futures) { try { names = f.get(); successfullTxCount++; } catch (Exception ex) { if (ex.getCause() instanceof OptimisticLockingFailureException) { // safely ignore since this is what we are testing. } else { throw new BackendException(ex); } } } es.shutdown(); assertTrue("Only 1 TX succeeded", successfullTxCount == 1); DetachedCriteria compCrit = DetachedCriteria.forClass(Company.class); Company c = hbc.findFirstByCriteria(compCrit, EMergeMode.MERGE_LAZY, Company.class); assertTrue("the company name is the one of the successfull TX", names.contains(c.getName())); for (Department d : c.getDepartments()) { assertTrue("the department name is the one of the successfull TX", names.contains(d.getName())); } }
From source file:database.DataLoader.java
private void moveDirections() throws SQLException, ClassNotFoundException, Exception { try {//from w ww. j a va 2 s .c om final String tableName = SPHERE; final ResultSet set = getFromOldBase(getSelectAll(tableName)); while (set.next()) { TransactionTemplate temp = new TransactionTemplate(transactionManager); temp.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus ts) { Long oldId = null; try { oldId = set.getLong("id"); String name = set.getString("name"); Direction dir = new Direction(); dir.setName(name); saveObjectAndLink(dir, oldId, tableName); } catch (Exception e) { addErrorMessage("direction: " + oldId + " " + StringAdapter.getStackExeption(e)); log.warn("direction: " + oldId + " " + StringAdapter.getStackExeption(e)); } } }); } } catch (Throwable th) { log.warn("moveDirections " + StringAdapter.getStackExeption(th)); } }
From source file:database.DataLoader.java
private void moveOrderTypes() throws SQLException, ClassNotFoundException, Exception { try {/* w w w. j a va 2 s. c om*/ final String tableName = TYPE; final ResultSet typeSet = getFromOldBase(getSelectAll(tableName)); while (typeSet.next()) { TransactionTemplate temp = new TransactionTemplate(transactionManager); temp.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus ts) { Long oldId = 0L; try { oldId = typeSet.getLong("id"); String name = typeSet.getString("name"); OrderType orderType = new OrderType(); orderType.setName(name); saveObjectAndLink(orderType, oldId, tableName); } catch (Exception e) { ts.setRollbackOnly(); addErrorMessage("type: " + oldId + " " + StringAdapter.getStackExeption(e)); } } }); } } catch (Throwable th) { log.warn("moveTypes " + StringAdapter.getStackExeption(th)); } }
From source file:database.DataLoader.java
private void moveOrderReadyFiles() throws Exception { ResultSet set = getOrderReadyFilesFromOldBase(); while (set.next()) { initFtpClient();// w w w . j ava 2s . co m try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new OrderReadyFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:database.DataLoader.java
private void moveAuthorMessageFiles() throws Exception { ResultSet set = getAuthorMessageFiles(); while (set.next()) { initFtpClient();/*from w w w .j ava 2s.co m*/ try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new AuthorMessageFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:database.DataLoader.java
private void moveAdminMessageFiles() throws Exception { ResultSet set = getAdminMessageFiles(); while (set.next()) { initFtpClient();// w w w. j a va2 s. c om try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new AdminMessageFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:database.DataLoader.java
private void moveOrderFiles() throws Exception { ResultSet set = getOrderFilesFromOldBase(); while (set.next()) { initFtpClient();/* www.j av a 2s.c o m*/ try { final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new OrderFileTransactionCallback(set)); } finally { logoutFtpClient(); } } }
From source file:database.DataLoader.java
private void moveAuthorReject() throws Exception { final String tableName = AUTHOR_REJECT; final ResultSet set = getFromOldBase(getSelectAll(tableName)); final List<AuthorReject> allList = authorRejectDao.getAll(); while (set.next()) { TransactionTemplate temp = new TransactionTemplate(transactionManager); temp.execute(new TransactionCallbackWithoutResult() { @Override/*from ww w . j av a2s .c o m*/ protected void doInTransactionWithoutResult(TransactionStatus ts) { String st = ""; try { Long oldAuthorId = set.getLong("author_id"); Long oldOrderId = set.getLong("order_id"); Long newAuthorId = getNewId(oldAuthorId, USERS); Long newOrderId = getNewId(oldOrderId, ORDER); st = "oldAuth" + oldAuthorId + " oldOrd" + oldOrderId + " newAuth" + newAuthorId + " newOrd" + newOrderId; Author author = getAuthor(newAuthorId); Order order = getOrder(newOrderId); AuthorReject authorReject = new AuthorReject(); authorReject.setAuthor(author); authorReject.setOrder(order); if (!exist(allList, author, order)) { authorRejectDao.save(authorReject); } } catch (Exception e) { ts.setRollbackOnly(); addErrorMessage("moveAuthorReject: " + st + StringAdapter.getStackExeption(e)); log.warn("moveAuthorReject: " + st + StringAdapter.getStackExeption(e)); } } }); } }