How properly "lifecycle" of a Hibernate session under Spring should be done?
The SessionFactory is created automatically by Spring and is taking its DB connections from Glassfish connection pool. At the moment I am getting a Hibernate session via SessionFactory.getCurrentSession(). Then I start transaction, do the work and then commit() or rollback() at the end. Do I need to do any other actions like disconnect(), close(), flush() or any others at any time so connections would be properly returned back to the pool or is everything already automatically done by Spring?
With plenty of these methods it is a little confusing for me at the moment to understand when what should be done, maybe someone can point to right direction?
As SessionFactory is created automatically by Spring, Spring framework will take care of closing the connection.
Check out Spring Resource Management
If you want to check. You can check the log, if you are using logging for your app. It'll be like :
(main) INFO [AnnotationSessionFactoryBean] Closing Hibernate SessionFactory
I get following lines from this link
The main contract here is the creation of Session instances. Usually
an application has a single SessionFactory instance and threads
servicing client requests obtain Session instances from this factory.
The internal state of a SessionFactory is immutable. Once it is
created this internal state is set. This internal state includes all
of the metadata about Object/Relational Mapping.
Implementors must be threadsafe.
The policies about how the connection releases back to the connection pool have nothing to do with Spring .It is configured by Hibernate itself through the configuration parameter hibernate.connection.release_mode , which is identified by the enum in the org.hibernate.ConnectionReleaseMode
Start from version 3.1+ , the default value of the hibernate.connection.release_mode is auto which the corresponding ConnectionReleaseMode value depends on whether JTA or JDBC transaction is used. In case of JDBC transaction is used , it is set to ConnectionReleaseMode.AFTER_TRANSACTION (i.e after_transaction ).
The behaviour of ConnectionReleaseMode.AFTER_TRANSACTION is that : The connection will be returned to the connection pool after each transaction , that is by calling either transaction.commit() or transaction.rollback() , as well as calling session.close() and session.disconnect()
You can verify this behaviour in hibernate documentation Section 11.5.
Hope this link will guide you about session and transactions.
Then I start transaction, do the work and then commit() or rollback()
at the end. Do I need to do any other actions like disconnect(),
close(), flush() or any others at any time so connections would be
properly returned back to the pool or is everything already
automatically done by Spring?
As you call commit() on Transaction it will automatically closes the session, which ultimately calls close method on connection to return to it's pool.
When you are executing a hibernate query through SessionFactory.getCurrentSession() , Spring performs the necessary task of opening and closing the connection . The SessionFactory you are using in the spring config also calls the config.buildSessionFactory method internally .
Most of this happens in the implementations of the AbstractSessionFactoryBean. The closing of connecting is done by hibernate in the SessionFactoryImpl class using the statement settings.getConnectionProvider().close(); . In short , hibernate does everything for you . Spring just calls it's help when necessary.
Related
I was understanding about spring + hibernate + java integration. So i got clear picture on below given points:
Spring uses LocalSessionFactoryBean class to create SessionFactory which is hibernate class.
Application context load the definition for datasource, hibernate properties etc.
we can inject SessionFactory class in spring dao classes.
My question is on crud operation invocation, like
sessionfactory.getCurrentSession().get(--, -)
How it works internally in terms of using datasource or any other spring/hibernate related resources ?
I try to explain at hight level what happen, for more detail you can check the source code.
First of all in your line of code 2 methods are called:
getCurrrentSession() on session factory
get(--,--) in the returned session
In the first method hibernate use the CurrentSessionContext to retreive the acual session. The CurrentSessionContext implementation substantially looks if there is an open session with an open transaction related to your thread and your session facotry and return it; to make it simpler it loooks if you are doing something on this DB in this thread and allow You to continue. If the CurrentSessionContext doesn't find a session a new one is create. (Note there are many implementation of CurrentSessionContext by default JPA one is used)
After retreive the session the second method is executed. In the second method referring to the dialect and other objects a native sql query is generated. In your specific case the sql is sent over the session to the database, the step looks like:
if the session is not binded to a connection, ask for a db connection from the pool
send the sql over the connection and retreive a resultset
get the resultset and tranlaste it to the entity object wich will be returned
if you are doing a dml operation (update, insert ...) the sql is tored on the session and it will be sent after flushing the session(you can use the flush() method it, otherwise just commit and wait hibernate do ti for you). Important note, committing the Transaction means that the code will be execute on the DB. After commit hibernate, with his own timing, will open a transaction over the db connection (important hibernate transacion is not a db transaction) will execute all the generate sql statement and will commit the DB transaction. This is the flush operation, remember yo don't exactally know when the flush happen since you don't force it manually with the flush() method.
hope this hepl
r.
As we all know that in Hibernate if no transaction commit, the changes won't affect in database. But I found something weird. And the code as follows:
ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring.xml");
SessionFactory sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
Session session = sessionFactory.openSession();
Model model = new Model();
...
session.save(model);
session.flush();
session.close();
And the model was saved to database even there's no transaction, anyone can explain this?
Any comments would be appreciated! Thanks!
PS: I am using mysql.
The session.flush command saved the transaction. If it's wrong, you should use transaction.
usually hibernate needs the line session.beginTransaction(); to work. You didn't write that and your application worked, I guess your application runs in an Application server, which provides transaction management. e.g. jboss, weblogic...
However it doesn't mean that there is no transaction. Did you set auto-commit true?
btw, session.flush() and txn.commit() are different.
Flushing is the process of synchronizing the underlying persistent store with persistable state held in memory.
After session.flush(), you still can call txn.rollback() to rollback all changes.
edit
oh I saw you used spring. did you configured txnmanager in spring?
Hibernate doesn't need transactions, the most common problems in database-based applications are just easier to solve with transactions which is why usually everyone uses transactions with Hibernate. But that's mere coincidence/convention/laziness.
All Hibernate needs is a java.sql.Connection and if your container provides one even though there is no current transaction manager configured, Hibernate is fine with that.
In fact, Hibernate has no idea that there might be a transaction manager. So session.flush() will use the ApplicationContext to get a connection, generate the SQL and use JDBC to send the generated SQL code to the database.
From Hibernate's point of view, that's all that happens.
There can be several reasons why the data is committed to the database:
You forgot to turn of auto commit on the connection.
Your web container / spring config automatically wires a transaction manager that synchronizes with HTTP requests.
Your code is called form another method which is annotated with #Transactional; in this case, you inherit the existing transaction.
Is there any way to remove/suspend a current spring managed hibernate session from a thread so a new one can be used, to then place the original session back onto the thread? Both are working on the same datasource.
To describe the problem in more detail. I'm trying to create a plugin for a tool who has it's own spring hibernate transaction management. In this plugin I would like to do some of my own database stuff which is done on our own spring transaction manager. When I currently try to perform the database actions our transaction manager starts complaining about an incompatibly transactionmanager already being used
org.springframework.transaction.IllegalTransactionStateException: Pre-bound JDBC Connection found! HibernateTransactionManager does not support running within DataSourceTransactionManager if told to manage the DataSource itself. It is recommended to use a single HibernateTransactionManager for all transactions on a single DataSource, no matter whether Hibernate or JDBC access.
A workaround that seems to do the trick is running my own code in a different thread and waiting for it to complete before I continue with the rest of the code.
Is there a better way then that, seems a bit stupid/overkill? Some way to suspend the current hibernate session, then open a new one and afterworths restoring the original session.
Is there any reason you can't have the current transaction manager injected into your plugin code? Two tx managers sounds like too many cooks in the kitchen. If you have it injected, then you should be able to require a new session before doing your work using the #transactional annotation's propagation REQUIRES_NEW attribute see the documentation for an example set-up
e.g.
#transactional(propogation = Propogation.REQUIRES_NEW)
public void addXXX(Some class) {
...
}
But this would use spring's PlatformTransactionManager rather than leaving it up to hibernate to manage the session / transaction.
I have a little of confusion about JDBC connection, transactions and their integration in EJB, JTA, Hibernate environment. My doubts are:
when we use #Resource DataSource ds; ... ds.getConnection() , are we working in the same transaction used by the managed bean? Should we close the connection, statement, resultset?
what about session.doWork? Are we in the same transaction? What about closing statement and result set?
aggressive release mode in Hibernate means that connections are closed after each statement. Does it mean that transaction is committed too? (I don't think this is true, but I can't understand how Hibernate works here)
There are a few things you need to figure out. First thing you need to identify what is your unit of work.
The session-per-request pattern is one of the most used and unless you have specific needs stick with that.
If you are using Hibernate you don't use statements and result sets directly. Hibernate will do that for you. what you need to close is the hibernate session
What you use is a SessionFactory and a Session object. The session pretty much represents your unit of work. Inside the hibernate session you get your objects, you change them and save them back.
The session per request pattern opens a session when a request is received and closes it when the response is sent back.
In a container managed EJB session bean a transaction is available and the datasource you (or hibernate) use in such a container is automatically handled by a JTA TransactionManager.
Now because Hibernate is smart it can automatically bind the "current" Session to the current JTA transaction.
This enables an easy implementation of the session-per-request strategy with the getCurrentSession() method on your SessionFactory:
try {
UserTransaction tx = (UserTransaction)new InitialContext()
.lookup("java:comp/UserTransaction");
tx.begin();
// Do some work
factory.getCurrentSession().load(...);
factory.getCurrentSession().persist(...);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e; // or display error message
}
So to answer your questions:
If you are using Hibernate with JTA in a container you'd be better off using a JPA EntityManager or maybe spring hibernate template.
Here are some references:
http://community.jboss.org/wiki/sessionsandtransactions#Transaction_demarcation_with_JTA
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/HibernateTemplate.html
I'm playing around with Spring + Hibernate and some "manual" transaction management with PostgreSQL
I'd like to try this out and understand how this works before moving to aop based transaction management.
#Repository
public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
#Override
public void saveUser(User u) {
Transaction tx = getSession().beginTransaction();
getHibernateTemplate().saveOrUpdate(u);
tx.rollback();
}
}
Calling saveUser here, I'd assume that saving a new User will be rolled back.
However, moving to a psql command line, the user is saved in the table.
Why isn't this rolled back, What do I have to configure to do transactions this way ?
Edit; a bit more debugging seems to indicate getHibernateTemplate() uses a different session than what getSession() returns (?)
Changing the code to
Transaction tx = getSession().beginTransaction();
getSession().persist(u);
tx.rollback();
and the transaction does get rolled back. But I still don't get why the hibernateTemplate would use/create a new session..
A couple of possibilities spring to mind (no pun intended):
a) Your JDBC driver defaults to autocommit=true and is somehow ignoring the beginTransaction() and rollback() calls;
b) If you're using Spring 3, I believe that SessionFactory.getSession() returns the Hibernate Session object wrapped by a Spring proxy. The Spring proxy is set up on the Session in part to handle transaction management, and maybe it's possible that it is interfering with your manual transaction calls?
While you can certainly use AOP-scoped proxies for transaction management, why not use the #Transactional(readOnly=false|true) annotation on your service layer methods? In your Spring config file for your service layer methods, all you need to do to make this work is to add
<tx:annotation-driven />
See chapters 10 and 13 of the Spring Reference Documentation on Transaction Management and ORM Data Access, respectively:
http://static.springsource.org/spring/docs/3.0.x/reference/index.html
Finally, if you're using Spring 3, you can eliminate references to the Spring Framework in your code by injecting the Spring-proxied SessionFactory bean into your DAO code - no more need to use HibernateDaoSupport. Just inject the SessionFactory, get the current Session, and use Hibernate according to the Hibernate examples. (You can combine both HibernateDaoSupport and plain SessionFactory-based Hibernate code in the same application, if required.)
If you see the JavaDoc for HibernateDaoSupport.getSession() it says it will obtain a new session or give you the one that is used by the existing transaction. In your case there isn't a transaction listed with HibernateDaoSupport already.
So if you use getHibernateTemplate().getSession() instead of just getSession(), you should get the session that is used by HibernateTemplate and then the above should work.
Please let me know how it goes.
EDIT:
I agree its protected...my bad. So the other option then is to keep the session thread bound which is usually the best practice in a web application. If HibernateDaoSupport is going to find a thread bound session then it will not create a new one and use the same one. That should let you do rollbacks.