简体   繁体   English

数据库操作后立即打开或关闭连接或在整个方法中使用相同的连接

[英]Open or close the connection instantly after DB operation or use same connection throughout method

i am working on a java web application where Database connection pooling is managed by tomcat-jdbc.我正在开发一个 java web 应用程序,其中数据库连接池由 tomcat-jdbc 管理。 I need to know which one is best practice 1.use same connection for multiple DB interactions in same method.我需要知道哪一个是最佳实践 1. 以相同的方法对多个数据库交互使用相同的连接。 2. Open and close the DB connection per DB operation 2.每个DB操作打开和关闭DB连接

Since the connection pool is managed by tomcat-jdbc , you'll most likely get an already existing connection from the pool instead of opening/closing a new connection each time, so from the performance point of view it shouldn't really matter if you get a new connection per operation or reuse the same connection per multiple operations.由于连接池由tomcat-jdbc管理,您很可能会从池中获得一个已经存在的连接,而不是每次都打开/关闭一个新连接,因此从性能的角度来看,如果您为每个操作获取一个新连接,或为多个操作重用相同的连接。

But you'll most likely need to execute all operations in the same method within the same database transaction (this depends on your use case).但是您很可能需要在同一数据库事务中以同一方法执行所有操作(这取决于您的用例)。 This implies that you'll also have to use the same connection for all of those operations.这意味着您还必须对所有这些操作使用相同的连接。

In general I would recommend to reuse the same connection for the scope of the method.一般来说,我建议对该方法的 scope 重复使用相同的连接。 An even better approach would be to use some high level framework that takes care of both database connections and transactions for you, eg Spring.更好的方法是使用一些高级框架来为您处理数据库连接和事务,例如 Spring。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM