List of usage examples for org.springframework.transaction.support TransactionCallback TransactionCallback
TransactionCallback
From source file:org.iti.agrimarket.model.dao.UserDAO.java
@Override public void destroy(Integer id) { User user = findUser(id);//from w w w. ja v a 2s. co m transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus ts) { try { Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); session.delete(user); return true; } catch (Exception e) { e.printStackTrace(); ts.setRollbackOnly(); } return false; } }); }
From source file:com.vladmihalcea.HibernateEagerSetTest.java
protected Long cleanAndSaveParent() { return transactionTemplate.execute(new TransactionCallback<Long>() { @Override/* www .ja v a 2 s . c o m*/ public Long doInTransaction(TransactionStatus transactionStatus) { entityManager.createQuery("delete from SetChild where id > 0").executeUpdate(); entityManager.createQuery("delete from SetParent where id > 0").executeUpdate(); assertTrue(entityManager.createQuery("from SetParent").getResultList().isEmpty()); SetParent parent = new SetParent(); entityManager.persist(parent); entityManager.flush(); return parent.getId(); } }); }
From source file:dao.MetricsDAO.java
public static ObjectNode getPagedMetrics(String dashboardName, String group, Integer page, Integer size, String user) {/* w ww . j av a 2s. c o m*/ Integer userId = UserDAO.getUserIDByUserName(user); final JdbcTemplate jdbcTemplate = getJdbcTemplate(); javax.sql.DataSource ds = jdbcTemplate.getDataSource(); DataSourceTransactionManager tm = new DataSourceTransactionManager(ds); TransactionTemplate txTemplate = new TransactionTemplate(tm); ObjectNode result; final Integer id = userId; result = txTemplate.execute(new TransactionCallback<ObjectNode>() { public ObjectNode doInTransaction(TransactionStatus status) { List<Map<String, Object>> rows; if (StringUtils.isBlank(dashboardName)) { rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS, id, (page - 1) * size, size); } else if (StringUtils.isBlank(group)) { String dbName; if (dashboardName.equals("[Other]")) { dbName = null; } else { dbName = dashboardName; } rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_NAME, id, dbName, dbName, (page - 1) * size, size); } else { String dbName; if (dashboardName.equals("[Other]")) { dbName = null; } else { dbName = dashboardName; } String grp; if (group.equals("[Other]")) { grp = null; } else { grp = group; } rows = jdbcTemplate.queryForList(SELECT_PAGED_METRICS_BY_DASHBOARD_AND_GROUP, id, dbName, dbName, grp, grp, (page - 1) * size, size); } List<Metric> pagedMetrics = new ArrayList<>(); for (Map row : rows) { Metric metric = new Metric(); metric.id = (int) row.get("metric_id"); metric.name = (String) row.get("metric_name"); metric.description = (String) row.get("metric_description"); metric.refID = (String) row.get("metric_ref_id"); metric.refIDType = (String) row.get("metric_ref_id_type"); metric.dashboardName = (String) row.get("dashboard_name"); metric.category = (String) row.get("metric_category"); metric.group = (String) row.get("metric_group"); metric.watchId = (Long) row.get("watch_id"); pagedMetrics.add(metric); } long count = 0; try { count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class); } catch (EmptyResultDataAccessException e) { Logger.error("Exception = " + e.getMessage()); } ObjectNode resultNode = Json.newObject(); resultNode.put("count", count); resultNode.put("page", page); resultNode.put("itemsPerPage", size); resultNode.put("totalPages", (int) Math.ceil(count / ((double) size))); resultNode.set("metrics", Json.toJson(pagedMetrics)); return resultNode; } }); return result; }
From source file:com.mothsoft.alexis.engine.numeric.TopicActivityDataSetImporter.java
private List<Long> listUserIds() { final List<Long> userIds = this.transactionTemplate.execute(new TransactionCallback<List<Long>>() { @SuppressWarnings("unchecked") @Override// www .j a v a 2 s . c o m public List<Long> doInTransaction(TransactionStatus txStatus) { final Query query = TopicActivityDataSetImporter.this.em .createQuery("SELECT id FROM User ORDER BY id ASC"); return query.getResultList(); } }); return userIds; }
From source file:org.pentaho.custom.authentication.provider.userroledao.hibernate.UserRoleDaoTransactionDecorator.java
public IRole getRole(final String name) throws UncategorizedUserRoleDaoException { return (IRole) transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { return userRoleDao.getRole(name); }/*w w w .j av a 2 s .c om*/ }); }
From source file:com.alibaba.otter.node.etl.load.loader.db.interceptor.operation.AbstractOperationInterceptor.java
private void init(final JdbcTemplate jdbcTemplate, final String markTableName, final String markTableColumn) { int count = jdbcTemplate .queryForInt(MessageFormat.format(checkDataSql, markTableName, GLOBAL_THREAD_COUNT - 1)); if (count != GLOBAL_THREAD_COUNT) { if (logger.isInfoEnabled()) { logger.info("Interceptor: init " + markTableName + "'s data."); }/*from w w w . j a v a 2 s. c o m*/ TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate .setTransactionManager(new DataSourceTransactionManager(jdbcTemplate.getDataSource())); transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);// ?????? transactionTemplate.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { jdbcTemplate.execute(MessageFormat.format(deleteDataSql, markTableName)); String batchSql = MessageFormat.format(updateSql, new Object[] { markTableName, markTableColumn }); jdbcTemplate.batchUpdate(batchSql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int idx) throws SQLException { ps.setInt(1, idx); ps.setInt(2, 0); // ps.setNull(3, Types.VARCHAR); } public int getBatchSize() { return GLOBAL_THREAD_COUNT; } }); return null; } }); if (logger.isInfoEnabled()) { logger.info("Interceptor: Init EROSA Client Data: " + updateSql); } } }
From source file:com.javaetmoi.core.persistence.hibernate.TestLazyLoadingUtil.java
/** * Verify the {@link LazyInitializationException} is thrown when accessing entity relations * outside a transaction, an Hibernate {@link PersistentMap} in this test. *///from w w w . j a v a 2 s. c om @Test(expected = LazyInitializationException.class) public void lazyInitializationExceptionOnPersistentMap() { // Load each entity in a transaction Employee dbJames = transactionTemplate.execute(new TransactionCallback<Employee>() { public Employee doInTransaction(TransactionStatus status) { Employee employee = (Employee) sessionFactory.getCurrentSession().get(Employee.class, 1); return employee; } }); // At this step, transaction and session are closed dbJames.getAddresses().get(0); }
From source file:org.ensembl.gti.seqstore.database.JdbcSeqStore.java
public long startSession(String clientId) { log.debug("Starting session for " + clientId); long id = transactionTemplate.execute(new TransactionCallback<Long>() { @Override/*from www . j a v a 2s . co m*/ public Long doInTransaction(TransactionStatus status) { KeyHolder keyHolder = new GeneratedKeyHolder(); template.update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement pst = con.prepareStatement(INSERT_SESSION_SQL, new String[] { "id" }); pst.setString(1, clientId); return pst; } }, keyHolder); return (Long) keyHolder.getKey(); } }); log.debug("New session " + id); return id; }
From source file:org.jasig.portlet.blackboardvcportlet.security.ConferenceUserPreAuthenticatedGrantedAuthoritiesUserDetailsService.java
protected ConferenceUser setupConferenceUser(final PortletAuthenticationDetails authenticationDetails) { final String uniqueId = getAttribute(authenticationDetails, this.uniqueIdAttributeName, true); final String mail = getAttribute(authenticationDetails, this.emailAttributeName, true); final String displayName = getAttribute(authenticationDetails, this.displayNameAttributeName, false); return this.transactionOperations.execute(new TransactionCallback<ConferenceUser>() { @Override/*w ww . j a v a 2 s . c o m*/ public ConferenceUser doInTransaction(TransactionStatus status) { ConferenceUser user = conferenceUserDao.getUserByUniqueId(uniqueId); if (user == null) { user = conferenceUserDao.createInternalUser(uniqueId); } boolean modified = false; //Update with current display name if (!StringUtils.equals(user.getDisplayName(), displayName)) { modified = true; user.setDisplayName(displayName); } //Update with current email if (!StringUtils.equals(user.getEmail(), mail)) { modified = true; user.setEmail(mail); } if (modified) { //Persist modification conferenceUserDao.updateUser(user); } return user; } }); }
From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelExecutorTask.java
private List<Long> findModelsToExecute() { return this.transactionTemplate.execute(new TransactionCallback<List<Long>>() { @Override/*from w w w. ja v a2 s.c o m*/ public List<Long> doInTransaction(TransactionStatus arg0) { final List<Model> models = OpenNLPMaxentModelExecutorTask.this.modelDao .findByTypeAndState(ModelType.MAXENT, ModelState.READY); final List<Long> modelIds = new ArrayList<Long>(models.size()); for (final Model model : models) { modelIds.add(model.getId()); } return modelIds; } }); }