Saturday, January 28, 2012

Solution to inserting record into the database

I tried to do it based on the Insert into ... Select standard query of HQL. This is only applicable to copy data from one object and add the content into another object. I could not proceed, just because i was trying to insert new records from a jsp page. The easier way to do it was ....
  • from the jsp page populate the data to the corresponding struts form class
  • do the persistence layer on to the entity generated by the hibernate 
  • using the struts corresponding action class save the form data in to the entity 
  • save the entity and execute the transaction after getting the session factory
look the struts action fragment code

data.setUsex(formObj.getUsex());

        try {
            SessionFactory _factory = (SessionFactory) context.getAttribute(HibernatePlugIn.SESSION_FACTORY_KEY);
            /*Open Hibernate Session */
            sess = _factory.openSession();
            sess.beginTransaction();
            sess.save(data);
            sess.getTransaction().commit();
        } catch (Exception e) {
            sess.getTransaction().rollback();
        }finally{
           
            sess.flush();
            sess.close();

No comments:

Post a Comment