Hi friends, I am making a program in which I want to access data from mysql through struts-hibernate integration. My search command is working properly but my delete and insert command gives output correctly but they don't update mysql table. Here is my program coding :
hibernate.cfg.xml: my configuration file
hibernate.hbm.xml my mapping file
InsertDataAction.java My insert data action class
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
package com.myapp.struts;
import java.sql.SQLException;
import org.hibernate.Query; import javax.servlet.ServletContext; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; /** * * @author pradeep.kundu */ public class InsertDataAction extends Action {
private static final String SUCCESS = "success"; private static final String FAILURE = "failure";
boolean flag; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionErrors errors = new ActionErrors(); InsertDataForm idf = new InsertDataForm(); Integer userId = idf.getuserId(); String firstName = idf.getfirstName(); String lastName = idf.getlastName(); Integer age = idf.getage(); Long number = idf.getnumber(); Session session = null; System.out.println("Getting session factory"); /*Get the servlet context */ try { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); ServletContext context = request.getSession().getServletContext(); /*Retrieve Session Factory */ SessionFactory _factory = (SessionFactory) context.getAttribute(HibernatePlugIn.SESSIONFACTORYKEY); /*Open Hibernate Session */ session = _factory.openSession();
String str = "INSERT INTO emp(userId,`firstName`,`lastName`,age,number)" + " VALUES (?,?,?,?,?) "; Query query = session.createSQLQuery(str); query.setParameter(0,userId); query.setParameter(1,firstName); query.setParameter(2,lastName); query.setParameter(3,age); query.setParameter(4,number); int row = query.executeUpdate(); // session.save(query); session.close(); saveErrors(request, errors); if (errors.isEmpty()) { flag = true; } else { flag = false; } } catch (Exception ex) { errors.add("SQLException", new ActionMessage("error.SQLException")); throw new SQLException(ex.fillInStackTrace()); } if (flag == true ) { return mapping.findForward(SUCCESS); } else { return mapping.findForward(FAILURE); }
} }
DeleteDataAction.java my delete data action class
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
package com.myapp.struts;
import org.hibernate.SessionFactory; import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration; import javax.servlet.ServletContext; import java.util.List; import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
/** * * @author pradeep.kundu */ public class DeleteDataAction extends Action {
private static final String SUCCESS = "success"; private static final String FAILURE = "failure"; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { List<String> listM = new ArrayList<String>(); DeleteDataForm sdf = (DeleteDataForm)form; Integer userId= sdf.getuserId(); System.out.println("Getting session factory");
/*Get the servlet context */ ServletContext context = request.getSession().getServletContext(); Session session = null; try { Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml"); /*Retrieve Session Factory */ SessionFactory _factory = (SessionFactory) context.getAttribute(HibernatePlugIn.SESSIONFACTORYKEY); /*Open Hibernate Session */ session = _factory.openSession();
String str = "delete from emp where userId = ? ";
Query query = session.createSQLQuery(str);
query.setParameter(0,userId);
//session.delete("from emp where userId ="+userId);
int row = query.executeUpdate();
if (row != 0){
listM.add("Record is successfully deleted");}
else {
listM.add("User Id not exit");
}
/*Close session */
session.close();
System.out.println("Hibernate Session Closed");
}
catch(Exception e){
System.out.println(e.getMessage());
}
request.setAttribute("listM", listM);
return mapping.findForward(SUCCESS);
}
}
SearchDataAction.java search action class
/* * To change this template, choose Tools | Templates * and open the template in the editor. */
package com.myapp.struts;
import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.criterion.Restrictions; import org.hibernate.Criteria;
import javax.servlet.ServletContext; import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
/** * * @author pradeep.kundu */ public class SearchDataAction extends Action {
private static final String SUCCESS = "success"; private static final String FAILURE = "failure"; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SearchDataForm sdf = (SearchDataForm)form; System.out.println("Getting session factory");
/*Get the servlet context */ ServletContext context = request.getSession().getServletContext(); /*Retrieve Session Factory */ SessionFactory _factory = (SessionFactory) context.getAttribute(HibernatePlugIn.SESSIONFACTORYKEY); /*Open Hibernate Session */ Session session = _factory.openSession(); //Criteria Query Example Criteria crit = session.createCriteria(Emp.class); crit.add(Restrictions.like("userId", sdf.getuserId())); //Fetch the result from database List tutorials= crit.list(); request.setAttribute("searchresult",tutorials); /*Close session */ session.close(); System.out.println("Hibernate Session Closed");
return mapping.findForward(SUCCESS);
} }
HibernatePlugin.java plugin file
package com.myapp.struts;
import java.net.URL; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.hibernate.HibernateException;
public class HibernatePlugIn implements PlugIn { private String _configFilePath = "/hibernate.cfg.xml";
/** * the key under which the <code>SessionFactory</code> instance is stored * in the <code>ServletContext</code>. */ public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName(); private SessionFactory _factory = null;
public void destroy() { try{ _factory.close(); }catch(HibernateException e){ System.out.println("Unable to close Hibernate Session Factory: " + e.getMessage()); }
}
public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { System.out.println("***********"); System.out.println("* Initilizing HibernatePlugIn ***"); Configuration configuration = null; URL configFileURL = null; ServletContext context = null;
try{ configFileURL = HibernatePlugIn.class.getResource(_configFilePath); context = servlet.getServletContext(); configuration = (new Configuration()).configure(configFileURL); _factory = configuration.buildSessionFactory(); //Set the factory into session context.setAttribute(SESSION_FACTORY_KEY, _factory); }catch(HibernateException e){ System.out.println("Error while initializing hibernate: " + e.getMessage()); } System.out.println("*************************************");
}
/** * Setter for property configFilePath. * @param configFilePath New value of property configFilePath. */ public void setConfigFilePath(String configFilePath) { if ((configFilePath == null) || (configFilePath.trim().length() == 0)) { throw new IllegalArgumentException( "configFilePath cannot be blank or null."); } System.out.println("Setting 'configFilePath' to '" + configFilePath + "'..."); _configFilePath = configFilePath; }
/*(SessionFactory) servletContext.getAttribute (HibernatePlugIn.SESSIONFACTORYKEY); */
}
Please tell me solution as soon as possible
Thanks & Regards Pradeep Kundu
Please visit the following link:
Ads