Changes in database session context persists with pooled connection reuse

允我心安 提交于 2021-02-05 07:17:10

问题


In my application I have multithreads that needs to access database and I am using apache.tomcat.jdbc.pool.DataSource as a JDBC connection pool.

In some cases users execute stored procedures that might affect the database session context/variables before executing another query to retrieve some data.

After a thread is finished, connection is closed but the way the pooled connections work, the connection is not actually closed but rather returned to the connection pool for reuse. The problem is similar to this question question.

The problem is that these variables usually affect the data retrieved from the database. So when another thread acquire a connection where these variables/context where set and then query the database the data retrieved is affected by the context/variables.

What is the best way to handle such an issue? I have outlined some solutions but not sure which is best practise and not how to implement them all?

Execute a Procedure / Statement that reset session / variables before releasing the connection back to the pool: This solution could work but the issue is my application use different databases. For now MySQL and Oracle are supported. For Oracle we have RESET_PACKAGE Procedure, but there is no equivalent for MySQL. Is there a way to do it in MySQL? also what if new databases are supported?

Is there a way to enforce or explicitly close the actual/physical connection instead of just returning it to the pool? or Is there a property to enforce pool to close the connection?

Does rollback to a savepoint revert db session variables / context?

Savepoint savepoint = connection.setSavepoint();
// execute some procedure connection that affect session
connection.rollback(savepoint);
connection.close();

Or is there any other way to enforce clearing of session or restart/close the actual connection?

My question is related to this question.


回答1:


On MySQL you might perform the sequence:

BEGIN;
COMMIT RELEASE;

as your validationQuery. The RELEASE part disconnects the current session and creates a new one (cf. MySQL Documentation).



来源:https://stackoverflow.com/questions/65796032/changes-in-database-session-context-persists-with-pooled-connection-reuse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!