我有一个 servlet,我在其中得到一个 Connection 对象,然后将其交给两个工作线程以进行各种活动。我现在需要在一个线程上添加一个事务。
如果我开始这样的事务:connection.setAutoCommit(false);
这会影响两个线程吗?我想会的。
我是否必须获得每个线程的单独连接?
谢谢
我有一个 servlet,我在其中得到一个 Connection 对象,然后将其交给两个工作线程以进行各种活动。我现在需要在一个线程上添加一个事务。
如果我开始这样的事务:connection.setAutoCommit(false);
这会影响两个线程吗?我想会的。
我是否必须获得每个线程的单独连接?
谢谢
我认为你正在做的是非常糟糕的做法。您不能在线程之间共享 JDBC 连接。
如果您在应用程序服务器(如 TOMCAT/JBoss/WebSphere/WebLogic)下运行,请使用适当的 DataSource 来获取您需要的连接。
查看您的 Application Server 文档以获取有关如何执行此操作的信息。
你的 servlet 中会有这样的东西:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
Connection c = null;
try {
c = ...; /* preferred way of getting a connection in your AppServer
// do what you need with your JDBC connection
} catch (Exception e) {
// handle errors
} finally {
c.close(); /* you will need another TRY/CATCH here */
}
}
同样,您的工作线程将具有以下内容:
public void run()
{
Connection c = null;
try {
c = ...; /* preferred way of getting a connection in your AppServer
// do what you need with your JDBC connection
} catch (Exception e) {
// handle errors
} finally {
c.close(); /* you will need another TRY/CATCH here */
}
}
最终,您可以auto commit
在单独的连接对象上设置您需要的任何内容。