0

I am using Spring JDBC 3.0.6. I also have legacy code which uses plain JDBC. There are methods in the legacy code which required java.sql.Connection object. I want to call this method from my Spring code. How can I pass the java.sql.Connection object?

If I take connection object from the datasource then I need to manage the return/release of this connection. Can I not just get the reference of a connection object which is in the transaction.

I am using annotation based configuration and aop based declarative transactions.

2 Answers 2

6

Use JdbcTemplate.execute(ConnectionCallback). The connection callback will have access to the connection which is automatically opened, closed and associated to the current transaction by Spring.

Sign up to request clarification or add additional context in comments.

Comments

0

Use the DataSourceUtils.getConnection method, this will retreive the connection associated with the transaction. Use DataSourceUtils.releaseConnection to release it (a noop if the connection is the one associated with the Transaction.

If the legacy code has util classes to open / close connection - you can just modify that to use the DataSourceUtils functions.

4 Comments

This will not work for me as I do not want to write release connection. Since spring provides all the connection handling I want to stay away from that.
You don't have to call releaseConnection if you are sure that the connection you retreived was the one associated with Transaction.
How do I know that? I used DataSourceUtils.getConnection(datasource) and passed the datasource reference. I got the connection but the connection never returned.
The call needs to happen in the context of a spring managed transaction (a method annotated by @Transactional).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.