Configure Hibernate to obtain a fresh connection from a connection pool - java

How do I configure Hibernate so that each time I call sessionFactory.openSession() it connects with a new connection from the connection pool? The connection pool is managed by Websphere Application Server and is a JDBC Data Source.
Thanks

How do I configure Hibernate so that each time I call sessionFactory.openSession() it connects with a new connection from the connection pool?
This is the default behavior, each session will get a dedicated connection from the connection pool.
Right now, it appears that both sessions are using the same connection, because when the first session is closed (manually calling session.close()) sometimes, the other session will throw a "session closed" exception when trying to run more queries on it.
No they are not. But maybe the second connection gets released at the end of the transaction initiated for the request. Have a look at the hibernate.connection.release_mode configuration parameter, you might want to use on_close. But without more details on your transaction strategy, it's impossible to say anything.
The second session is open by a child thread which means that the child thread can keep living even after the (HTTP) request is complete.
Take my previous advice with a grain of salt, you should just not spawn unmanaged threads and I don't know how the application server will behave. I explain in this other answer what would be the right way.

Related

Datasource Microsoft JDBC Driver for SQL Server (AlwaysOn Availability Groups)

I have a question related to the scenario when connecting from a Java application using the Microsoft JDBC Driver 4.0 to a SQL Server 2014 with AlwaysOn Availability Groups set up for high availability.
With this set up, we will be connecting to an availability group listener (specified in the db connecting string instead of any particular instance), so that the DB fail-over etc. is handled gracefully by the listener and it tries to connect to the next available instance behind the scenes if current primary goes down in the AG cluster.
Question(s) I have is,
In the data-source that is configured on the j2ee application server side (we use WebSphere), what happens to those connections already pooled by the data-source?
When a database goes down, though the AG listener would try to reconnect on the db side to the next available DB, will the AG Listener also through the jdbc driver send an event or something to the data-source created on the app server and make sure those connections that are already pooled by the datasource to be discarded and have it create new ones so that transactions on the application side wont fail (though they might for a while till new connections are created and fail over is successful) or the java application has to find out only after requesting it from the datasource?
WebSphere Application Server is able to cope with bad connections and removes them from the pool. Exactly when this happens depends on some configurable options and on how fully the Microsoft JDBC driver takes advantage of the javax.sql.ConnectionEventListener API to send notifications to the application server. In the ideal case where a JDBC driver sends the connectionErrorOccurred event immediately for all connections, WebSphere Application Server responds by removing all of these connections from the pool and by marking any connection that is currently in-use as bad so that it does not get returned to the pool once the application closes the handle. Lacking this, WebSphere Application Server will discover the first bad connection upon next use by the application. It is discovered either by a connectionErrorOcurred event that is sent by the JDBC driver at that time, or lacking that, upon inspecting the SQLState/error code of an exception for known indicators of bad connections. WebSphere Application Server then goes about purging bad connections from the pool according to the configured Purge Policy. There are 3 options:
Purge Policy of Entire Pool - all connections are removed from
the pool and in-use connections marked as bad so that they are not
pooled.
Purge Policy of Failing Connection Only - only the
specific connection upon which the error actually occurred is
removed from the pool or marked as bad and not returned to the pool
Purge Policy of Validate All Connections - all connections are
tested for validity (Connection.isValid API) and connections found
to be bad are removed from the pool or marked as bad and not
returned to the pool. Connections found to be valid remain in the
pool and continue to be used.
I'm not sure from your description if you are using WebSphere Application Server traditional or Liberty. If traditional, there is an additional option for pre-testing connections as they are handed out of the pool, but be aware that turning this on can have performance implications.
That said, the one thing to be aware of is that regardless of any of the above, your application will always need to be capable of handling the possibility of errors due to bad connections (even if the connection pool is cleared, connections can go bad while in use) and respond by requesting a new connection and retrying the operation in a new transaction.
Version 4 of that SQL Server JDBC driver is old and doesn't know anything about the always on feature.
Any data source connection pool can be configured to check the status of the connection from the pool prior to doling it out to the client. If the connection cannot be used the pool will create a new one. That's true of all vendors and versions. I believe that's the best you can do.

Strange Behaviour when not closing hibernate session

I faced a problem regarding closing a hibernate session , The problem detail is:
UI(Implemented using JSF2.1 ) hangs after doing some action many times resulting with an empty request. The cause of the problem is the hibernate session does not close after doing any database action
So my question why has this hanging happened ? why an empty request? I think when something like this happens an exception will like IllegalStateException would be thrown by hibernate API to tell you "you have a lot of sessions opened " right ?
When you don't close your Hibernate sessions and therefore do not release JDBC connections, you have what is typically called Connection leak. So, after a number of requests (depending on the size of your connection pool) the server will not be able to acquire a connection to respond your request. Actually, server will be waiting for connections to be released and be available on pool again and it will seem to be hanging.

Is the connection Pool configuration kept outside JPA Context?

Hello i am extracting the connection object from the EclipseLink context by calling: Connection con = entityManager.unwrap(Connection.class);
i am responsible for releasing the Connection in order it to comeback into the pool however i need to know if the extracted connection is supposed to keep the original configuration set by EclipseLink i mean number of connections, Maximum number of connections and so on..if so then once it is returned into EclipseLink it is supposed to keep the same performance than working normally..
i need to know this cause maybe the experience of someone can help me in choosing if getting the connection in this way will keep a good performance as EclipseLink does when working its native JPA, thanks in advance..
You can only unwrap the Connection in the scope of a transaction. So you will get the same connection that the EntityManager is bound to (from the pool). You must not release this connection, EclipseLink will release when the transaction ends.
So, to be clear, you are NOT responsible for releasing the connection.

JDBC Connection Link Failure - How to fail over?

I have a stand-alone Java windows application developed based on Swing. It connects to a MySQL database for data storage. In case the database connection fails, I am getting a link failure exception from the MySQL JDBC driver (MySQLNonTransientConnectionException). I don't want to re-instantiate my database connection object or the whole program in case such a link failure issue happens. I just want to tell the user to try again later without having to restart the entire application. If the user is asked to restart the entire application, that would probably give a negative impression on the quality of the program. What do you think would be the preferred way for a standard java application to fail-over after such a database link failure without having to re-instantiate all the communication objects? Thanks in advance.
Use a Connection Pool (such as C3PO or DBCP). Your application takes the Connections from the pool, executes the statement(s) and puts the Connection back into the pool. The pool can be configured to test the JDBC Connections. For example, if they become stale, they can be automatically reinstantiated by the pool.
If your application takes the Connection from the pool, it will be a valid Connection. Let the pool handle the management of valid/invalid/stale JDBC Connections.

db2 jdbc driver does not release table locks

situation: We have a web service running on tomcat accessing DB2 database on AS400, we are using JTOPEN drivers for JNDI connections handled by tomcat. For handling transactions and access to database we are using Spring.
For each select system takes JDBC connection from JNDI (i.e. from connection pool), does selection, and in the end it closes ResultSet, Statement and releases Connection in that order. That passes fine, shared lock on table dissappears.
When we want to do update the same way as we did with select (exception on ResultSet object, we don't have one in such situation), after releasing Connection to JNDI lock on table stays.
If we put maxIdle=0 for number of connections in JNDI configuration, this problem disappears, but this degrades performances, we have cca 100 users online on that service, we need few connections to be alive in pool.
What do you suggest?
Sounds like as if the auto-commit is by default disabled and that the code isn't calling connection.commit() anywhere. To fix this, either configure the connection pool so that it only returns connections with autoCommit = true, or change the JDBC code that it commits the transaction at end of the try block wherein the SQL action is been taken place.
Take a look at this.
It helped me in the same case.

Categories