How to get current Connection object used by jdbcTemplate - java

I am looking for a way to intercept the connection that JDBCTemplate creates internally i.e. the connection that is created when the function getConnection() is called by JDBCTemplate.
ex: if I use jdbcTemplate.update(query); I want to get the information of the connection that was used to complete this update statement. Is there a way to see the metadata of the connection mid or post execution of this statement ? I am using C3P0 connection pool.
Many people have suggested using DataSourceUtils.getConnection() , but that just fetches a new connection from the pool and does not solve my issue.
This thread also effectively asks the same question: How to get current Connection object in Spring JDBC

jdbcTemplate.getDataSource().getConnection();
By using the above line we can fetch the connection object.

Related

Creation of new database connection in java using oracle jdbc template

/* connection pool created with 5 connections based on the region specific.
with below code it will get connection from connection pool which is already created.*/
Connection con = DatasourceClient.getDataSourceMap.get(region).getConnection();
OracleConnection oConn = con.unwrap(oracle.jdbc.OracleConnection.class);
Will above code will get two connections from pool and do i need to close both con and Oconn ?
i am getting pool exhausted and connection closed exceptions tried many ways by changing pool properties.
So just want to know what above code is doing.
tried closing the above connections but didn't get any difference results.
Using Oracle Jdbc template instead of spring jdbc because in my procedures there are array values which in few cases only input, in some cases only output and other both INOUT.
Can any one help me in this please ? Thank you.
No, it will get only a single connection out, which you then unwrap to it's actual class.
However you will need to call con.close() (and never oCon.close()) to return the connection back to the pool. This is because the wrapper's close() doesn't actually close the connection, it returns it back to the pool.

Use session bean to hold datasource connection [duplicate]

I'm running a web application on Tomcat. I have a class that handles all DB queries.
This class contains the Connection object and methods that returns query results.
This is the connection object:
private static Connection conn = null;
It has only one instance (singleton).
In addition, I have methods that execute queries, such as search for a user in the db:
public static ResultSet searchUser(String user, String pass) throws SQLException
This method uses the static Connection object. My question is, is my use in static Connection object thread safe? Or can it cause problems when a lot of users will call the searchUser method?
is my use in static Connection object thread safe?
Absolutely not!
This way the connection going to be shared among all requests sent by all users and thus all queries will interfere with each other. But threadsafety is not your only problem, resource leaking is also your other problem. You're keeping a single connection open during the entire application's lifetime. The average database will reclaim the connection whenever it's been open for too long which is usually between 30 minutes and 8 hours, depending on DB's configuration. So if your web application runs longer than that, the connection is lost and you won't be able to execute queries anymore.
This problem also applies when those resources are held as a non-static instance variable of a class instance which is reused multiple times.
You should always acquire and close the connection, statement and resultset in the shortest possible scope, preferably inside the very same try-with-resources block as where you're executing the query according the following JDBC idiom:
public User find(String username, String password) throws SQLException {
User user = null;
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, username, email FROM user WHERE username=? AND password=md5(?)");
) {
statement.setString(1, username);
statement.setString(2, password);
try (ResultSet resultSet = statement.executeQuery()) {
if (resultSet.next()) {
user = new User();
user.setId(resultSet.getLong("id"));
user.setUsername(resultSet.getString("username"));
user.setEmail(resultSet.getString("email"));
}
}
}
return user;
}
Note that you should not return a ResultSet here. You should immediately read it and map it to a non-JDBC class and then return it, so that the ResultSet can safely be closed.
If you're not on Java 7 yet, then use a try-finally block wherein you manually close the closeable resources in the reverse order as you've acquired them. You can find an example here: How often should Connection, Statement and ResultSet be closed in JDBC?
If you worry about connecting performance, then you should be using connection pooling instead. This is built-in into many Java EE application servers and even barebones servletcontainers like Tomcat supports it. Just create a JNDI datasource in the server itself and let your webapp grab it as DataSource. It's transparently already a connection pool. You can find an example in the first link of the list below.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
When my app loses connection, how should I recover it?
Am I Using JDBC Connection Pooling?
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
DAO tutorial with JDBC
If you are only running Select queries (searchUser sounds like only selecting data) there will be no issues, apart from thread contention.
As far as I know, a Connection can only handle one query at a time, so by using a single instance you will essentially serialize database access. But this does not necessarily mean, it is always safe to access a database like this in a multi threaded environment. There might still be issues if concurrent accesses are interleaving.

Reuse open connection from BasicDataSource

I am creating a new BasicDataSource object and set in it username, password, etc.
Once i call the dataSource.getConnection(), a new connection is created.
My requirement is to able to reuse the already opened connection.
In the Java Doc of getConnection() it is written:
Create (if necessary) and return a connection to the database
Which apparently i can't understand WHEN is this necessary.
There is a setMaxActive that limits the maximum connections, but this looks to be kind of limiting currently for me as once the getConnection() is called, it tries to create a new connection with the database instead of getting the existing one.
Question: Is there away to set somehow the DataSource in that way in order to create just one connection and to retrieve the same connection always when getConnection() is called ? Any other workaround ?

How to verify the connection object returned from connection pool?

I am doing jndi lookup for datasource configured in JBOSS AS.Code for which is as below.
initialContext = new InitialContext(props);
dataSource =
(DataSource)initialContext.lookup(bundle.getString("jndiName"));
connection = dataSource.getConnection();
This snippet of code is placed in doPost of servlet. Also i am safely calling
connection.close()
after using connection object.
My datasource config has following entries
<min-pool-size>1</min-pool-size>
<max-pool-size>1</max-pool-size>
As per my understanding of connection pooling, each time i make a request to servlet same connection object is returned by datasource .getConnection() call(Since i have specified min and max pool size to be 1 and a call to close does not close the DB connection altogether).
Now how do i verify that same connection object is being returned?
You actually can't be sure that it is the same connection. It maybe problems with connection with database, so another connection had to be created. Why you want to verify connection? Maybe you could save hash value and compare them?

ResultSet Object is closed - jtds

I am using JTDS to connect to MS-SQL 2005. I am using c3p0 as the DB Connection pool, configured with Spring.
I am randomly getting an SQLException: Invalid state, the ResultSet object is closed in a Groovy script in which I have passed a reference to the connection pool. The script is executed by a timer every so often. By random, I mean that the script works perfectly 99% of the time, but when it fails, it will do so a couple of times, then go back to working correctly again, picking up where it left off. All of the critical work is done in a transaction, pulling off of a Message Queue.
Logic below:
//passed into the groovy context
DataSource source = source;
Connection conn = source.getConnection();
...
//Have to omit proprietary DB stuff... sorry...
PreparedStatement fooStatement = conn.prepareStatement("INSERT INTO foo (x,y,z) VALUES (?,?,?) select SCOPE_IDENTITY();");
ResultSet identRes = fooStatement.executeQuery();
//This is where the execption is thrown.
identRes.next();
...
try{
log.info("Returning SQL connection.");
conn.close();
}catch(Exception ex){}
There is a separate timer thread that runs a similar groovy script, in which we have not seen this issue. That script uses similar calls to get the connection, and close it.
Originally, we thought that the second script may have been grabbing the same connection off the pool, finishing first, then closing the connection. But c3p0's documentation says that calling conn.close() should simply return it to the pool.
Has anyone else seen this, or am I missing something big here?
Thanks.
We solved this... C3P0 was configured to drop connections that were checked out longer than 30 seconds, we did this to prevent dead-lock in the database (we don't control the tuning). One of the transactions was taking horridly long to complete, and C3P0 was dropping the connection, resulting in the ResultSet Closed error. Surprisingly, however, C3P0 was not logging the incident, so we didnt see this in the application's logs.

Categories

Resources