public Object execGroovyRetObjByDbTran(String groovyName, String methodName, Object... paramArray) throws Exception{ /* MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType); DataSource dataSource=microDao.getMicroDataSource(); PlatformTransactionManager transactionManager=new DataSourceTransactionManager(dataSource);*/ PlatformTransactionManager transactionManager=MicroTranManagerHolder.getTransactionManager(dbName); DefaultTransactionDefinition def =new DefaultTransactionDefinition(); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus status=transactionManager.getTransaction(def); try { Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray); transactionManager.commit(status); return retObj; } catch(Exception ex) { transactionManager.rollback(status); throw ex; } }
/** * 补偿的时候,不走分布式事务处理 * * @param point point 切点 * @param info 信息 * @return Object * @throws Throwable */ @Override public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable { TxTransactionLocal.getInstance().setTxGroupId(CommonConstant.COMPENSATE_ID); DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def); try { final Object proceed = point.proceed(); platformTransactionManager.commit(transactionStatus); LogUtil.info(LOGGER, "补偿事务执行成功!事务组id为:{}", info::getTxGroupId); return proceed; } catch (Throwable e) { LogUtil.info(LOGGER, "补偿事务执行失败!事务组id为:{}", info::getTxGroupId); platformTransactionManager.rollback(transactionStatus); throw e; } finally { TxTransactionLocal.getInstance().removeTxGroupId(); CompensationLocal.getInstance().removeCompensationId(); } }
@Override public SaveResult<T> doInTransaction(final TransactionStatus status) { final SaveResult<T> result; try { wijzigObjectVoorOpslag(item); if (historieVerwerkers.isEmpty()) { result = new SaveResult<>(repository.save(item)); } else { final T managedItem = repository.findOrPersist(item); for (final HistorieVerwerker<T> historieVerwerker : historieVerwerkers) { historieVerwerker.accept(item, managedItem); } result = new SaveResult<>(repository.save(managedItem)); } } catch (final NotFoundException e) { return new SaveResult<>(e); } return result; }
Ticket getTicketInTransaction(final String ticketId) { return new TransactionTemplate(txManager).execute(new TransactionCallback<Ticket>() { @Override public Ticket doInTransaction(final TransactionStatus status) { return jpaTicketRegistry.getTicket(ticketId); } }); }
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(final TransactionStatus status) { try { final Object result = method.invoke(jpaLock, args); jpaLock.entityManager.flush(); logger.debug("Performed {} on {}", method.getName(), jpaLock); return result; // Force result of transaction to database } catch (final Exception e) { throw new RuntimeException("Transactional method invocation failed.", e); } } }); }
@Override public boolean deleteBook(long ISBN) { // TODO Auto-generated method stub if (searchBook(ISBN).getISBN() == ISBN) { transactionTemplate.setReadOnly(false); return transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { // TODO Auto-generated method stub try { boolean result = bookDAO.deleteBook(ISBN); return result; } catch (Exception exception) { status.setRollbackOnly(); } return false; } }); } return false; }
public synchronized void run(boolean useIndex) { if (useIndex) { jdbcTemplate.query(sql, setter, rowHandler); } else { long latest = latestFetcher.retrieveLatestSer(); transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { jdbcTemplate.execute("SET LOCAL enable_bitmapscan=0;"); jdbcTemplate.query(sql, setter, rowHandler); return null; } }); // shift to max(retrievedLatestSer, and ser as updated in // rowHandler) serialToContinueFrom.set(Math.max(serialToContinueFrom.get(), latest)); } }
/** * {@inheritDoc} */ @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() { public Object doInTransaction(final TransactionStatus status) { try { final Object result = method.invoke(jpaLock, args); jpaLock.entityManager.flush(); logger.debug("Performed {} on {}", method.getName(), jpaLock); return result; // Force result of transaction to database } catch (final Exception e) { throw new RuntimeException("Transactional method invocation failed.", e); } } }); }
public <T> T tx(TransactionRun<T> run) { TransactionStatus txStatus = getTransactionStatus(); T result; try { result = run.run(); } catch (RuntimeException re) { transactionManager.rollback(txStatus); throw re; } catch (Error err) { transactionManager.rollback(txStatus); throw err; } catch (Exception e) { transactionManager.rollback(txStatus); throw new UndeclaredThrowableException(e, "undeclared error happened in transaction"); } transactionManager.commit(txStatus); return result; }
@Override public Object invoke(Object o, Method method, Object[] objects) throws Throwable { Sql sql = this.sql; if (method.getDeclaringClass() == SqlStreamHolder.class) { return sql; } TransactionStatus transactionStatus = null; try { transactionStatus = TransactionAspectSupport.currentTransactionStatus(); } catch (NoTransactionException e) { if (FAIL_WITHOUT_TRANSACTION) { throw e; } } if (transactionStatus instanceof SqlStreamTransactionStatus) { sql = ((SqlStreamTransactionStatus) transactionStatus).transaction; } return method.invoke(sql, objects); }
@Override public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException { Transaction.IsolationLevel isolationLevel = translateIsolationLevel(definition.getIsolationLevel()); Transaction t; if (isolationLevel == null) { t = sql.transaction(); } else { t = sql.transaction(isolationLevel); } if (definition.isReadOnly()) { Wrap.execute(() -> t.getConnection().setReadOnly(true)); } return new SqlStreamTransactionStatus(t); }
public Object execGroovyRetObjByDbTranNest(String groovyName, String methodName, Integer nestDef, Object... paramArray) throws Exception{ /* MicroMetaDao microDao=MicroMetaDao.getInstance(dbName,dbType); DataSource dataSource=microDao.getMicroDataSource(); PlatformTransactionManager transactionManager=new DataSourceTransactionManager(dataSource);*/ PlatformTransactionManager transactionManager=MicroTranManagerHolder.getTransactionManager(dbName); DefaultTransactionDefinition def =new DefaultTransactionDefinition(); def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); if(nestDef==null){ nestDef=TransactionDefinition.PROPAGATION_REQUIRED; } def.setPropagationBehavior(nestDef); TransactionStatus status=transactionManager.getTransaction(def); try { Object retObj= GroovyExecUtil.execGroovyRetObj(groovyName, methodName, paramArray); transactionManager.commit(status); return retObj; } catch(Exception ex) { transactionManager.rollback(status); throw ex; } }
/** * 删除Channel */ public void remove(final Long channelId) { Assert.assertNotNull(channelId); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { try { arbitrateManageService.channelEvent().destory(channelId); channelDao.delete(channelId); } catch (Exception e) { logger.error("ERROR ## remove channel has an exception ", e); throw new ManagerException(e); } } }); }
/** * 删除 */ public void remove(final Long pipelineId) { Assert.assertNotNull(pipelineId); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { try { PipelineDO pipelineDO = pipelineDao.findById(pipelineId); if (pipelineDO != null) { pipelineDao.delete(pipelineId); pipelineNodeRelationDao.deleteByPipelineId(pipelineId); // 删除历史cursor String destination = pipelineDO.getParameters().getDestinationName(); short clientId = pipelineDO.getId().shortValue(); arbitrateViewService.removeCanal(destination, clientId); arbitrateManageService.pipelineEvent().destory(pipelineDO.getChannelId(), pipelineId); } } catch (Exception e) { logger.error("ERROR ## remove the pipeline(" + pipelineId + ") has an exception!"); throw new ManagerException(e); } } }); }
/** * 添加 */ public void create(final DataMatrix matrix) { Assert.assertNotNull(matrix); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { DataMatrixDO matrixlDO = modelToDo(matrix); matrixlDO.setId(0L); matrixlDO.setGroupKey(matrixlDO.getGroupKey()+TimeUtil.getTime0()); if (!dataMatrixDao.checkUnique(matrixlDO)) { String exceptionCause = "exist the same repeat canal in the database."; logger.warn("WARN ## " + exceptionCause); throw new RepeatConfigureException(exceptionCause); } dataMatrixDao.insert(matrixlDO); } catch (RepeatConfigureException rce) { throw rce; } catch (Exception e) { logger.error("ERROR ## create canal has an exception!"); throw new ManagerException(e); } } }); }
/** * 删除 */ public void remove(final Long matrixId) { Assert.assertNotNull(matrixId); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { dataMatrixDao.delete(matrixId); } catch (Exception e) { logger.error("ERROR ## remove canal(" + matrixId + ") has an exception!"); throw new ManagerException(e); } } }); }
/** * 修改 */ public void modify(final DataMatrix matrix) { Assert.assertNotNull(matrix); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { DataMatrixDO matrixDo = modelToDo(matrix); if (dataMatrixDao.checkUnique(matrixDo)) { dataMatrixDao.update(matrixDo); } else { String exceptionCause = "exist the same repeat matrix in the database."; logger.warn("WARN ## " + exceptionCause); throw new RepeatConfigureException(exceptionCause); } } catch (RepeatConfigureException rce) { throw rce; } catch (Exception e) { logger.error("ERROR ## modify canal(" + matrix.getId() + ") has an exception!"); throw new ManagerException(e); } } }); }
/** * 删除 */ public void remove(final Long canalId) { Assert.assertNotNull(canalId); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { Canal canal = findById(canalId); canalDao.delete(canalId); arbitrateViewService.removeCanal(canal.getName()); // 删除canal节点信息 } catch (Exception e) { logger.error("ERROR ## remove canal(" + canalId + ") has an exception!"); throw new ManagerException(e); } } }); }
/** * 添加 */ public void create(final Node node) { Assert.assertNotNull(node); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { NodeDO nodeDo = modelToDo(node); nodeDo.setId(0L); if (!nodeDao.checkUnique(nodeDo)) { String exceptionCause = "exist the same repeat node in the database."; logger.warn("WARN ## " + exceptionCause); throw new RepeatConfigureException(exceptionCause); } nodeDao.insert(nodeDo); } catch (RepeatConfigureException rce) { throw rce; } catch (Exception e) { logger.error("ERROR ## create node has an exception!"); throw new ManagerException(e); } } }); }
@Override public Book searchBook(long ISBN) { // TODO Auto-generated method stub transactionTemplate.setReadOnly(true); return transactionTemplate.execute(new TransactionCallback<Book>() { @Override public Book doInTransaction(TransactionStatus status) { // TODO Auto-generated method stub // Book book = bookDAO.serachBook(ISBN); Book book=new Book(); book.setISBN(ISBN); bookDAO.addBook(book); return book; } }); }
/** * 修改 */ public void modify(final Node node) { Assert.assertNotNull(node); transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult(TransactionStatus status) { try { NodeDO nodeDo = modelToDo(node); if (nodeDao.checkUnique(nodeDo)) { nodeDao.update(nodeDo); } else { String exceptionCause = "exist the same repeat node in the database."; logger.warn("WARN ## " + exceptionCause); throw new RepeatConfigureException(exceptionCause); } } catch (RepeatConfigureException rce) { throw rce; } catch (Exception e) { logger.error("ERROR ## modify node(" + node.getId() + ") has an exception!"); throw new ManagerException(e); } } }); }
public Object doInTransaction(TransactionStatus status) { try { failedDatas.clear(); // 先清理 processedDatas.clear(); interceptor.transactionBegin(context, Arrays.asList(data), dbDialect); JdbcTemplate template = dbDialect.getJdbcTemplate(); int affect = template.update(data.getSql(), new PreparedStatementSetter() { public void setValues(PreparedStatement ps) throws SQLException { doPreparedStatement(ps, dbDialect, lobCreator, data); } }); interceptor.transactionEnd(context, Arrays.asList(data), dbDialect); return affect; } finally { lobCreator.close(); } }
/** * 处理补偿内嵌的远程方法的时候,不提交,只调用 * * @param point point 切点 * @param info 信息 * @return Object * @throws Throwable 异常 */ @Override public Object handler(ProceedingJoinPoint point, TxTransactionInfo info) throws Throwable { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus transactionStatus = platformTransactionManager.getTransaction(def); try { return point.proceed(); } finally { platformTransactionManager.rollback(transactionStatus); } }
@Override public void appendTransLog(final String appId, final String busCode, final String trxId, final List<Content> newOrderedContent, final boolean finished) { transactionTemplate.execute(new TransactionCallback<Object>(){ @Override public Object doInTransaction(TransactionStatus status) { JdbcTemplate localJdbcTemplate = getJdbcTemplate(); //unfinished tag localJdbcTemplate.update("insert into `trans_log_unfinished` VALUES(?,?) on DUPLICATE KEY UPDATE create_time = create_time;", EasyTransStaticHelper.getTransId(appId, busCode, trxId),new Date()); //concrete log int logUpdateConut = localJdbcTemplate.update("INSERT INTO `trans_log_detail` (`log_detail_id`, `trans_log_id`, `log_detail`, `create_time`) VALUES (NULL, ?, ?, ?);", EasyTransStaticHelper.getTransId(appId, busCode, trxId), objectSerializer.serialization(newOrderedContent), new Date() ); if(logUpdateConut != 1){ throw new RuntimeException("write log error!"); } if(LOG.isDebugEnabled()){ LOG.debug(newOrderedContent.toString()); } if(finished){ //remove unfinished tag localJdbcTemplate.update("DELETE FROM trans_log_unfinished WHERE trans_log_id = ?;", EasyTransStaticHelper.getTransId(appId,busCode,trxId)); } return null; } }); }
public void cleanFinishedLogs(String appId,final Date cleanBefore) { transactionTemplate.execute(new TransactionCallback<Object>(){ @Override public Object doInTransaction(TransactionStatus status) { JdbcTemplate localJdbcTemplate = getJdbcTemplate(); localJdbcTemplate.update("delete from trans_log_detail where create_time < ? and trans_log_id not in (select trans_log_id from trans_log_unfinished);",cleanBefore); return null; } }); }
private void updateTransactionOrderRefundStatus(PaymentStatusInfo statusInfo) throws Exception { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); def.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT); TransactionStatus status = txManager.getTransaction(def); try { if (statusInfo.getServiceStatus().equals(PaymentServiceStatus.SUCCESS)) { Integer tradeId = Integer.valueOf(statusInfo.getTradeId()); PaymentTransaction transactionPO = transactionMapper.selectByPrimaryKey(tradeId); if (null == transactionPO) { throw new KException("找不到对应交易号"); } PaymentStatus localStatus = PaymentStatus.valueOf(transactionPO.getStatus()); PaymentStatus remoteStatus = statusInfo.getStatus(); if (!localStatus.equals(remoteStatus)) { boolean validState = (localStatus.equals(PaymentStatus.SUCCESS) && remoteStatus.equals(PaymentStatus.APPLIED_REFUND)); validState |= (localStatus.equals(PaymentStatus.APPLIED_REFUND) && (remoteStatus.equals(PaymentStatus.REFUNDED) || remoteStatus.equals(PaymentStatus.REFUND_FAILED))); if (validState) { transactionPO.setStatus(remoteStatus.name()); transactionPO.setRefundTime(statusInfo.getPaymentTime()); getOrderCoordinator().updateRefundStatus(transactionPO.getOrderId(), transactionPO); transactionMapper.updateByPrimaryKeySelective(transactionPO); } else { logPaymentException(transactionPO.getOrderId(), tradeId, localStatus.name(), remoteStatus.name(), "交易状态错误"); } } } } catch (Exception e) { txManager.rollback(status); throw e; } txManager.commit(status); }
public static Object createFolderAction(final String name, final String path, final String children, final Long datasetId, final boolean flag, final Long bindId) { TransactionTemplate transactionTemplate = getTransactionTemplate(); Object object = transactionTemplate.execute(new TransactionCallback<Object>() { public Object doInTransaction(TransactionStatus status) { int res = 0; try { // insert the record and get the folder id. KeyHolder keyHolder = new GeneratedKeyHolder(); getJdbcTemplate().update(new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = getJdbcTemplate().getDataSource().getConnection(). prepareStatement(CREATE_LOGIC_DATASET_FOLDER, new String[]{ "title" ,"path"}); ps.setString(1, name); ps.setString(2, path); return ps; } }, keyHolder); res = keyHolder.getKey().intValue(); if (res <= 0) throw new Exception(); String childrenList = children + (children.length() == 0?children:",") + res; int row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_CHILDREN, childrenList, datasetId); if (row <= 0) throw new Exception(); if (!flag) { row = getJdbcTemplate().update(UPDATE_LOGIC_DATASET_DATASETID, bindId, 0, res); if (row <= 0) throw new Exception(); } } catch (Exception e) { status.setRollbackOnly(); e.printStackTrace(); } return res; } }); return object; }
/** * Сохранить календарь. */ public void save() { QLog.l().logger().info("Save the calendar ID = " + calcId); final DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setName("SomeTxName"); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); TransactionStatus status = Spring.getInstance().getTxManager().getTransaction(def); try { final LinkedList<FreeDay> dels = new LinkedList<>(); for (FreeDay bad : days_del) { boolean f = true; for (FreeDay good : days) { if (good.equals(bad)) { f = false; } } if (f) { dels.add(bad); } } Spring.getInstance().getHt().deleteAll(dels); Spring.getInstance().getHt().saveOrUpdateAll(days); } catch (Exception ex) { Spring.getInstance().getTxManager().rollback(status); throw new ClientException( "Error performing the operation of modifying data in the database (JDBC).\nPerhaps you added a new calendar, changed it, tried to save the contents of the calendar, but did not save the overall configuration.\nSave the entire configuration (Ctrl + S) and try again to save the contents of the calendar.\n\n[" + ex.getLocalizedMessage() + "]\n(" + ex.toString() + ")"); } Spring.getInstance().getTxManager().commit(status); QLog.l().logger().debug("Saved a new calendar"); //Type so that there are actual internal data days_del = new ArrayList<>(days); }
void addTicketInTransaction(final Ticket ticket) { new TransactionTemplate(txManager).execute(new TransactionCallback<Object>() { @Override public Void doInTransaction(final TransactionStatus status) { jpaTicketRegistry.addTicket(ticket); return null; } }); }
void deleteTicketInTransaction(final String ticketId) { new TransactionTemplate(txManager).execute(new TransactionCallback<Void>() { @Override public Void doInTransaction(final TransactionStatus status) { jpaTicketRegistry.deleteTicket(ticketId); return null; } }); }
ServiceTicket grantServiceTicketInTransaction(final TicketGrantingTicket parent) { return new TransactionTemplate(txManager).execute(new TransactionCallback<ServiceTicket>() { @Override public ServiceTicket doInTransaction(final TransactionStatus status) { final ServiceTicket st = newST(parent); jpaTicketRegistry.addTicket(st); return st; } }); }
ProxyGrantingTicket grantProxyGrantingTicketInTransaction(final ServiceTicket parent) { return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyGrantingTicket>() { @Override public ProxyGrantingTicket doInTransaction(final TransactionStatus status) { final ProxyGrantingTicket pgt = newPGT(parent); jpaTicketRegistry.addTicket(pgt); return pgt; } }); }
ProxyTicket grantProxyTicketInTransaction(final ProxyGrantingTicket parent) { return new TransactionTemplate(txManager).execute(new TransactionCallback<ProxyTicket>() { @Override public ProxyTicket doInTransaction(final TransactionStatus status) { final ProxyTicket st = newPT(parent); jpaTicketRegistry.addTicket(st); return st; } }); }
@Override public String call() throws Exception { return new TransactionTemplate(txManager).execute(new TransactionCallback<String>() { @Override public String doInTransaction(final TransactionStatus status) { // Querying for the TGT prior to updating it as done in // CentralAuthenticationServiceImpl#grantServiceTicket(String, Service, Credential) final ServiceTicket st = newST((TicketGrantingTicket) jpaTicketRegistry.getTicket(parentTgtId)); jpaTicketRegistry.addTicket(st); return st.getId(); } }); }
@Override public boolean updateBook(long ISBN, int price) { // TODO Auto-generated method stub TransactionDefinition definition = new DefaultTransactionDefinition(); TransactionStatus transactionStatus = transactionManager.getTransaction(definition); if (searchBook(ISBN).getISBN() == ISBN) { int rows = bookDAO.updateBook(ISBN, price); if (rows > 0) { transactionManager.commit(transactionStatus); return true; } } return false; }
/** * 手动进行回滚事务. * 接口中如果 try catch 异常无法回滚时,这手动调用回滚处理 */ public static void rollback () { TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus(); if ( null != transactionStatus ) { transactionStatus.setRollbackOnly(); } }
public void deleteUser(final int uid) { //use TransactionCallbackWithoutResult handler if ur query doesnt result anything transactionTemplate.execute(new TransactionCallbackWithoutResult() { protected void doInTransactionWithoutResult( TransactionStatus paramTransactionStatus) { try{ String delQuery = "delete from users where id = ?"; jdbcTemplate.update(delQuery, new Object[]{uid}); }catch (Exception e) { //use this to rollback exception in case of exception paramTransactionStatus.setRollbackOnly(); } } }); }
@Override public boolean addBook(Book book) { // TODO Auto-generated method stub if (searchBook(book.getISBN()).getISBN() == 98564567l) { transactionTemplate.setReadOnly(false); return transactionTemplate.execute(new TransactionCallback<Boolean>() { @Override public Boolean doInTransaction(TransactionStatus status) { // TODO Auto-generated method stub try { int rows = bookDAO.addBook(book); if (rows > 0) return true; } catch (Exception exception) { status.setRollbackOnly(); } return false; } }); } return false; }
private void beginTransaction(Context ctx) { DefaultTransactionDefinition def = new DefaultTransactionDefinition(); if (timeout > 0) { def.setTimeout(timeout); } TransactionStatus tx = tm.getTransaction(def); ctx.put(TX, tx); }