Related to this question (where the answer doesn\'t really get to the point):
Hiberate with Struts2 - Use Full Hibernate Plugin or another method to close Sessions?<
Okay, as noone's got an answer, I looked into the question and the code again and googled a bit.
Fact 1: The plugin is only supported till Struts 2.1.6, additionally I'm using the new Tomcat 7, so I guessed that something might just not work with the plugin.
Fact 2: Someone in a Hibernate Forum pointed out, that this problem can arise if you try to access the session instead of opening a new one: Hibernate Forum:Session is Closed! (solution near the bottom)
It seem that fact 1 lead to the Annotations of @session
and @transaction
not working correctly, or I was using them wrong, as they were often null in my prepare method, which is such a class and from which all my struts2 actions are derived:
public abstract class ActionHelper extends ActionSupport implements Preparable, ...
In this class, I used the following Annotations that usually worked in all other projects so far (Struts 2.1.6 and Tomcat 6):
@SessionTarget
Session db;
@TransactionTarget
Transaction transaction;
private FeedGroupDAO _feedGroupDao;
In the prepare method, I had defensive programming code that checked if the session was null and then replaced it by the current hibernate session. The problem was that this session was often times closed, what you can find out if you ask if (!session.isOpen())
Therefore now I use the following code in my prepare method in the ActionHelper class:
public void prepare() throws Exception {
// initialize DAO Objects with Session and Transaction
if (session == null)
{
session = com.googlecode.s2hibernate.struts2.plugin.util.HibernateSessionFactory.getNewSession();
if (!session.isOpen())
throw new NullPointerException("Fix the code: session's not here");
transaction = session.beginTransaction();
}
_feedGroupDao = new FeedGroupDAO(session,transaction); // init more DAOs with the same session/transaction
The getNewSession()
method of the plugin seems to use Hibernate's openSession()
internally, therefore this seems to be the working solution from the Hibernate-forums. Additionally, this still supports the OpenSessionInView pattern as the struts2-fullhibernate-plugin is managing the session and transaction you got from the static getNewSession()
method. As a sidenote, I try to move away from defensive programming to throwing exceptions as soon as possible ;-)
Hope this could help you.