会话会话= sessionFactory.openSession();是不是在休眠

问题描述 投票:-1回答:1

我正在尝试集成hibernate和struts2。没有错误。但是根本没有创建会话。以下是我的代码。 CustomerAction.java

    public String addCustomer(Customer customer) throws Exception{

        //get hibernate session from the servlet context
        SessionFactory sessionFactory =
             (SessionFactory) ServletActionContext.getServletContext()
                     .getAttribute(HibernateListener.KEY_NAME);
        System.out.println("session factory accessed");
        Session session = sessionFactory.openSession();
        System.out.println("session created");

        //save it


        session.beginTransaction();
        System.out.println("Transaction begin");
        session.save(customer);
        session.getTransaction().commit();
}

hibernate listener.Java

    public class HibernateListener implements ServletContextListener{

    private Configuration config;
    private SessionFactory factory;
    private String path = "/hibernate.cfg.xml";
    private static Class clazz = HibernateListener.class;

    public static final String KEY_NAME = clazz.getName();

    public void contextDestroyed(ServletContextEvent event) {
      //
    }

    public void contextInitialized(ServletContextEvent event) {

     try {
         SessionFactory sessionFactory =
                    new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
            System.out.println("session factory created");

            //save the Hibernate session factory into serlvet context
            event.getServletContext().setAttribute(KEY_NAME, factory);
      } catch (Exception e) {
             System.out.println(e.getMessage());
       }
    }
}

在struts.xml

<struts>
  <constant name="struts.devMode" value="false" />

  <package name="default" namespace="/" extends="struts-default">

    <action name="addCustomer"
    class="com.mkyong.customer.action.CustomerAction">
       <result name="success">WEB-INF/pages/customer.jsp</result>
    </action>

      </package>
</struts>

代码没有给出任何错误,但数据库中没有插入数据。

hibernate struts2
1个回答
0
投票

使用Hibernate手动集成Struts2浪费时间。您可能无法确切地知道如何配置会话工厂或在上下文侦听器中执行此操作。在任何其他情况下,您的代码无效。

但是有一种方法可以通过插件直接集成Struts2和hibernate。您可以看到this回答提供的示例。

在Struts2中有一个名为Struts2 Full Hibernate Plugin或的非官方插件,它提供了与Hibernate的集成。有例子:

© www.soinside.com 2019 - 2024. All rights reserved.