Does using spring JdbcTemplate create a new connection to the sql server? - sql

Everytime you use spring JdbcTemplate, does it actually create a new connection to the sql server ?

Answer 1:
In short yes it does close the connection. The long answer it depends.
When you don’t have a Spring managed transaction then yes the JdbcTemplate will call the close() method on the Connection. However if there was already a connection available due to Springs transaction management closing the connection will be handled by Springs transaction support, which in turn also will call close() on the Connection.
The only difference is when the connection is closed but close() will be called.
If the connection will be actually closed depends on which DataSource is used, in general when using a connection pool the connection will be returned to the pool instead of actually closing the connection.
Answer 2:
Yes it does.
And if the connection was obtained from connection pool, it won’t actually close the connection, rather will send it back to the pool.
Answer 3:
No need to close the connection manually. Spring container itself to take of the operation. Kindly refer this spring url,
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html
Answer 4:
We can also close connection while using jdbcTemplete, in some cases it compulsory to close connection after execute query otherwise getting connection issue. for more details visit
[Close connection in jdbc template][1] [1]: http://www.javaiq.in/2019/05/jdbctemplate.html
Link is: https://inneka.com/programming/spring/does-springs-jdbctemplate-close-the-connection-after-query-timeout/

Understanding datasource interface is the key to understanding the answer to this question. JdbcTemplate has a dependency on datasource and official javadoc for DataSource interface says:
Datasource is a factory for connections to the physical data source that this datasource object represents.
It means every-time a JdbcTemplate is used for executing a SQL query, it requests a connection from the datasource. Datasource retrieves a connection from the connection pool, if available, and gives it to JdbcTemplate. JdbcTemplate then executes the SQL query and releases the connection back to the pool.
So, yes, we would need a new connection every-time JdbcTemplate is used for executing a SQL query but that connection is always fetched from the connection pool that any implementation of Datasource interface maintains.
Maintaining a connection pool is lot more time efficient than creating a new connection on demand. Obviously, considering memory limits, there has to be an upper cap on the connection pool size.

Related

What is SQL Connection [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What SQL Connection object is and what does actually happen when we open/close it? What resources does it consume and why is it necessary to dispose it (in terms of c#/.net)?
SqlConnection:
Take a look at the MSDN page for SqlConnection. It is stated that:
A SqlConnection object represents a unique session to a SQL Server
data source. With a client/server database system, it is equivalent to
a network connection to the server.
SqlConnection.Open: In the MSDN page on SqlConnection.Open, it is stated that:
The SqlConnection draws an open connection from the connection pool if
one is available. Otherwise, it establishes a new connection to an
instance of SQL Server.
SqlConnection.Close(and Dispose):
The MSDN page on SqlConnection.Close says that:
The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.
Also, in the SqlConnection page it is stated that:
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.
and:
To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
This should answer your questions.
EDIT:
For further readings (also seen in your comments) you can read about Connection-Pooling and of course check out the source code for SqlConnection.
Sql Connection object in an object which we create using Sql connection class which belongs to System.Data.SqlClient namespace. We use Sql Connection object to execute sql commands in sql server database.
Close and Dispose are two different things. You can reuse the connection if you close it but not after dispose it.
It is always a good practice to open the connection just before you want it and close it once done your needs.
In c#, the connection will be disposed if you create the connection with “using” statement.

How long should you keep an ODBC SQL connection open?

A long-running application uses the MS C OBDC API to create and use SQL connections to an Oracle DB. The application was originally designed to establish an ODBC connection at startup and keep that connection indefinitely as the application runs, potentially for weeks or months.
We're seeing very infrequent cases where a connection suddenly dies and I wondered if that's because we're using them wrong, or if it's considered OK to hold a connection like this. Can anyone point me to some definitive information on the subject?
I'm not sure there's definitive information regarding this, but with long-running programs you always have to be prepared for this kind of incidents, they just happen (and not only with db connections but also with sockets that remain open for extended periods). I have no experience with Oracle, but I have a very similar setup with Informix, and this is (in pseudocode) what we do
while (programissupposedtorun) {
opendb();
do {
youractivities();
} while(dbisok);
closedbandcleanup();
}
As long as you are able to correctly detect that the connection died and are able to resume processing without losing data you should be OK.
I'm not familiar with ODBC but such use cases are best handled with a connection pool. Your application can simply request a connection from the pool when it has some work and release it as soon as its done -- the pool will take care of actually (re)connecting to the database.
A quick search for ODBC connection pooling brought this up: Driver Manager Connection Pooling

NHibernate Connection Pooling

I am considering using Fluent NHibernate for a new application with SQL Server 2008 and I am having trouble understanding the connection handling behavior I am seeing.
I am monitoring connections using sp_who2 and here is what I see:
When the SessionFactory is created, a single connection is opened. This connection
seems to stay open until the app is killed.
No connection is opened when a new session is opened. (That's ok, I understand NHibernate waits until the last moment to create database connections).
No new connection is opened even when I run a query through NHibernate. I must assume it is using the connection created when the SessionFactory was created, which is still open. I set a breakpoint after the query (before the session was closed), and no new sessions had appeared in sp_who.
Running an entire app through a single connection is not acceptable (obviously). How can I ensure each ISession gets its own connection? I'm sure there's something obvious I'm missing here...
Thanks in advance.
The behaviour that you see is nothing NHibernate specific - Connection pooling is default behaviour in SQL Server.
Even if it may sound awkward at first glance, it actually is a good thing because creating new connections and maintaining them is expensive.
(for more information, see the Wikipedia article about connection pooling)
So there is no need to try to get NH to open a new connection for each session, because reusing existing connections actually improves SQL Server performance.

NHibernate ISessionFactory.OpenSession() does not open a database connection

I have NHibernate configured with Fluent NNibernate connecting to a PostgreSQL database.
I have a worker class that takes an ISessionFactory as a constructor parameter and consumes messages from a queue. For each message the worker process calls ISessionFactory.OpenSession() and it does some database processing.
When I add more worker processes the performance of the system remains the same which is odd.
After some more investigation I realized that all worker processes are using a single database connection. For example I would add 8 worker processes but on the database I can see only one database connection.
My understanding is that ISessionFactory.OpenSession() will open a new database connection unless the Connection Pool is full.
So is my understanding wrong or is this and issue with the Postgres NHibernate driver.
OpenSession does not open a database connection until needed, and it closes it (i.e. releases it back into the pool) as soon as possible.
By default the session will keep the connection open for the life time of a transaction and as Diego said, it only opens it when needed.
If you want to manage your own connections you can call
ISessionFactory.OpenSession(myConnection);

Closing SQL connections (NHibernate)

I have a test console app that is executing sql scripts to create a database and its tables, then inserting data. I use DAO to create, retrieve, update, and delete from the tables and then try and drop the database, but it can't because it says it is currently in use. How do I kill the connection? Through debugging and running a sql script to see the total connections, I've narrowed it down to this piece of code that is not killing the connection. Even though it says the connections are cleared, the database says it is still connected.
foreach (ISessionFactory factory in this.connections.Values)
{
factory.Close();
}
this.connections.Clear();
this.connections = null;
NHibernate manages all the database connections itself. It opens and closes the database as it sees fit, but you can try to call Session.Disconnect to get it to disconnect from the ADO.NET connection.
However ... if you have Connection Pooling enabled, which is normally the 'default' connection behavior, the connection will only be returned to the connection pool, not released, and it will still show as a connection, so you would have to clear the connection pool.
Unfortunately, I do not know if you can do this directly thru NHibernate, but you can use a SQLConnection object to issue a ClearPool or ClearAllPools call ...