Struts2 + Full Hibernate Plugin --> Session is Closed?

♀尐吖头ヾ 提交于 2019-12-01 01:54:47

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!