我该怎么做休眠嵌套事务只使用一个连接?(How do I do nested transaction

2019-09-17 21:06发布

Context of problem I want to solve: I have a java spring http interceptor AuditHttpCommunicationInterceptor that audits communication with an external system. The HttpClieant that does the communication is used in a java service class that does some business logic called DoBusinessLogicSevice. The DoBusinessLogicSevice opens a new transaction and using couple of collaborators does loads of stuff.

Problem to solove: Regardless of the outcome of any of the operations in DoBusinessLogicSevice (unexpected Exceptions, etc) I want audits to be stored in the database by AuditHttpCommunicationInterceptor.

Solution I used: The AuditHttpCommunicationInterceptor will open a new transaction this way:

    TransactionDefinition transactionDefinition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
    new TransactionTemplate(platformTransactionManager, transactionDefinition).execute(new TransactionCallbackWithoutResult() {
        @Override
        protected void doInTransactionWithoutResult(TransactionStatus status) {
            // do stuff
        }
    });

Everything works fine. When a part of DoBusinessLogicSevice throws unexpected exception its transaction is rolled back, but the AuditHttpCommunicationInterceptor manages to store the audit in the database.

Problem that arises from this solution: AuditHttpCommunicationInterceptor uses a new db connection. So for every DoBusinessLogicSevice call I need 2 db connections. Basicly, I want to know the solution to the problem: how to make TransactionTemplate "suspend" the current transaction and reuse the connection for a new one in this case.

Any ideas? :)

P.S. One idea might be to take a different design approach: drop the interceptor and create an AuditingHttpClient that is used in DoBusinessLogicSevice directly (not invoked by spring) but I cannot do that because I cannot access all http fields in there.

Answer 1:

Spring支持嵌套事务(传播=“嵌套”),但是这确实取决于数据库平台上,我不相信每一个数据库平台能够处理嵌套事务。

我实在看不出有什么大不了与服用从池中连接,做一个快速的审计事务,并返回连接回来。

更新:虽然Spring支持嵌套事务,它看起来像Hibernate不。 如果是这样的话,我说:去审核另一个连接。



文章来源: How do I do nested transactions in hibernate using only one connection?