且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPA中的事务使用多个线程

更新时间:2023-02-01 07:51:15

几个问题想到这一点 -

Few questions that come to mind -

全局交易

您的所有线程都应该属于同一个交易吗?这意味着,如果一个线程抛出异常,你想要回滚其他线程中的更改吗?

Global Transaction
Should all of your threads be part of the same transaction? The implications are that, if a thread throws an exception, do you want to rollback changes in other threads?

本地交易
每个线程是否应该拥有自己的事务边界而不影响其他线程?在这种情况下,一个线程中的异常和回滚不会影响其他线程。

Local Transaction Should each thread have it's own transaction boundary with out affecting other threads? In this case, the exceptions and rollbacks in one thread do not affect other threads.

要实现全局事务,您很可能必须使用具有适当资源驱动程序的JTA事务管理器。 Spring没有对全局事务的默认支持。如果您的应用程序在Java EE应用程序服务器(Jboss,Weblogic)中运行,则默认情况下您将获得JTA支持,您可以配置spring以使用应用程序服务器的事务管理功能。
如果你在tomcat中运行,你可以插入一个开源的JTA实现,如 -

To achieve global transactions, you will most likely have to use a JTA transaction manager with appropriate resource drivers. Spring does not have default support for global transactions. If your application is running in a Java EE application server (Jboss, Weblogic), you get JTA support by default and you could configure spring to use your application server's transaction management capabilities. If you are running in tomcat, you could plugin an open source JTA implementation like -

Atomikos

Jboss Transactions

为了实现本地交易(即每个线程都有自己的交易边界),我认为你不必再做任何事了而不是使用spring transactional annotations。
在下面的示例中,只需确保'service'是一个spring bean并且doSomething()被适当地注释。

To achieve local transactions (i.e., each thread with it's own transaction boundaries), I don't think you will have to do anything more than use spring transactional annotations. In the following example, just make sure that 'service' is a spring bean and doSomething() is appropriately annotated.

taskExecutor.execute( new Runnable() {
           public void run() {
                service.doSomething( );
           }
      });