1

I am trying to integrate hibernate and struts2. There is no error. But the session is not created at all.Following is my code.

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();
}

HibernateListener.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>

The code is not giving any error but no data is inserted in database.

Roman C
  • 49,761
  • 33
  • 66
  • 176

1 Answers1

0

There's a way to integrate Struts2 and hibernate directly via plugin. You can see the examples provided by this answer.

In Struts2 there's unofficial plugin called Struts2 Full Hibernate Plugin or that provides an integration with Hibernate. There're examples:

Roman C
  • 49,761
  • 33
  • 66
  • 176
  • Thanks. But I took help of http://www.mkyong.com/struts2/struts-2-hibernate-integration-example/. And the above code is like this only. – sujata salunkhe Dec 26 '17 at 08:50