Home Answers Viewqa Hibernate Access data from mysql through struts-hibernate integration

 
 


pradeep Kundu
Access data from mysql through struts-hibernate integration
1 Answer(s)      a year ago
Posted in : Hibernate

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

org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/employee root 1234 10 true org.hibernate.dialect.MySQLDialect update save

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

View Answers

May 11, 2012 at 3:56 PM


Please visit the following link:

http://www.roseindia.net/struts/struts-hibernate/









Related Pages:
Access data from mysql through struts-hibernate integration
Access data from mysql through struts-hibernate integration  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
Struts Hibernate Integration
and Hibernate Integration. You can download the source code from here... Struts Hibernate       Hibernate is Object-Oriented mapping tool that maps the object view of data
struts hibernate integration application
also use annotation as mapping metadata. About struts hibernate integration... of the struts hibernate integration application example. Description...Struts2 hibernate integration application. In this tutorial we are going
access data from mysql through struts
access data from mysql through struts  I am Pradeep Kundu. I am making a program in struts in which i want to access data from MySQL through struts. I am using Strut 1.3.8 , Netbean 6.7.1 and MySQL 5.5. In this program ,I want
Integrating Struts and Hibernate
Integrating Struts and Hibernate           This article explains the integration of Struts... Hibernate in your Struts project. We will be using Hibernate Struts plug
Downloading Struts & Hibernate
called Struts-Hibernate-Integration. 2. Unzip Downloaded file...:\Struts-Hibernate-Integration\code" and the content of struts-blank.war... files from "hibernate-3.1\lib" to "C:\Struts-Hibernate
Struts - Hibernate Integration
link: Struts Hibernate Integration Thanks...Struts - Hibernate Integration  Hi, I need to integrate the struts with hibernate.. can u pls tell me the process of configuring etc etc WITHOUT
struts and hibernate integration
struts and hibernate integration  i want entire for this application using struts and hibernate integration here we have to use 4 tables i.e... the following link: Struts Hibernate Integration
Struts-Hibernate-Integration - Hibernate
Struts-Hibernate-Integration  Hi, I was executing struts hibernate intgeration code the following error has occured. Anyone can give me... the following link: http://www.roseindia.net/struts/struts-hibernate/ Hope
Migrating from mysql to MS Access
Migrating from mysql to MS Access  Hi I am hoping for some help I need to write a conversion program (SQL statements) to import existing data in a MYSQL database to a MS Access database. any suggestions would be appreciated
Building and Testing Struts Hibernate Plugin Application
will build and test our Struts Hibernate Integration application. Compiling... console and go to "C:\Struts-Hibernate-Integration\code\WEB-INF\src"...;C:\Struts-Hibernate-Integration\dist" directory. Deploying and testing
Access all the fields from table through JSP
Access all the fields from table through JSP... data from the specified table. Before running this java code you need.... This is first jsp page that has a link 'show data from table', which displays all
How to access (MySQL)database from J2ME?
How to access (MySQL)database from J2ME?  I am new to J2ME. I am using NetBeans. Can anyone help me? How to access (MySQL)database from J2ME? ( I search a lot I found that there is need to access database through servlet
Understanding Spring Struts Hibernate DAO Layer
Hibernate DAO Layer   The Data Access Object for this application is written... Understanding Spring Struts Hibernate DAO Layer... how Spring Hibernate and Struts will work together to provide best solution
Data retrieve from mysql database
Data retrieve from mysql database  Hi sir, please give some example... text field using struts and hibernate. Regards Subrat   The given... from the dropdown, related data will get displayed on the textboxes. Here we have
Integration
the following link: http://www.roseindia.net/struts/hibernate-spring/index.shtml Thanks   http://www.roseindia.net/struts/hibernate-spring/index.shtml...Integration  How to integrate struts with spring in MyEeclipse
Access Excel file through JDBC
Access Excel file through JDBC In this section, you will learn how to access excel file through Jdbc and display records in JTable. As you know Excel comes... all the data using ResultSet. To create a new ODBC Data Source, follow
Data Access Object
interface to access data. The DAO given with application, uses hibernate to access data from database. Hibernate contains java some classes and .xml files...Creating Data Access Object (DAO) Design Pattern The Data Access Object
struts+hibernate
struts+hibernate  org.hibernate.InvalidMappingException: Could not parse mapping document from resource roseindia/net/hibernate/Address.hbm.xml
Accessing Database from servlets through JDBC!
Accessing Access Database From Servlet    This article shows you how to access database from servlets... and run the servlet. Your browser should display the data from
EAI - Enterprise Application Integration EAI,Enterprise Application Integration,EAI Technology,EAI software
business processes and data are to be integrated etc. Apart from this initial... not have database or business process-level access may be accessed through... technology. Screen scrapping is the copying of data from specific locations
update data to mysql database through JTextField
update data to mysql database through JTextField  I am getting an error, when i am updating a data to mysql database through JTextField. Send me...(); JOptionPane.showMessageDialog(null,"Data successfully Updated to the database
struts with hibernate - Hibernate
struts with hibernate  Can u send me Realtime example of struts with hibernate(Saving,Delete,update,select from muliple tables
accessing ms access through jsp
accessing ms access through jsp  i have 3 tables in my database employee,project,task if i put employee id the search field .i should get details from other table what all queries should i use in servlet file and i am using
Integration Libraries
Integration Libraries Java Database Connectivity (JDBC) API Using this API, you can fetch the data from databases, Flat files or Spread sheet. Remote Method Invocation (RMI) Using this API, you can create distributed java
struts hibernate integraion tut - Struts
struts hibernate integraion tut  Hi, I was running struts hibernate integration tutorial. I am facing following error while executing the example. type Exception report message description The server encountered
integration with struts 2.0 & spring 2.5 - Framework
integration with struts 2.0 & spring 2.5  Hi All, The total integration is Client (JSP Page) --- Struts 2.0--Spring 2.5 --- Hibernate 3.0--MySQL... the data in form i am catching them in the struts action class. So in action class I
Integrate Struts, Hibernate and Spring
Integrate Struts, Hibernate and Spring   ... are using one of the best technologies (Struts, Hibernate and Spring). This tutorial.... Download Struts: The latest version of Struts can be downloaded from http
myfaces,hibernate and spring integration - Hibernate
_hibernate" inside ur MySql. 7)save the jdbc.properties file 8)run the server 9...myfaces,hibernate and spring integration  sorry, in the previous... followed:- 1) downloaded the .zip file from ur website. 2)then unzipped it. 3
How to access session values through Ajax?
How to access session values through Ajax?  Suppose in a servlet a variable userName is kept in session. How can I access this variable from JSP through AJAX? Is it possible
Struts+Hibernate - Development process
Struts+Hibernate  Hi I am Using Struts+Hibernate in my web... records from the form using lazy validator. and i got one local bean where i could copy all the records that i retrieved from the form .but i am getting
Retrieve The Data From MySql Datbase
Retrieve The Data From MySql Datbase   How to Retrieve The Data From MYSQL database TO Use Select the Emp_id Option.And Also Search Option
Need to access data from another application
Need to access data from another application  Hi Tech masters, I want to develop a reporting application.for that I need to access data from a third party application. I want to access data from a software called service
retreiving data from microsoft access database
retreiving data from microsoft access database  How can i retrieve data from microsoft access when i have select the vaules in combo box and text box. When i select these values... i want to retrieve the corresponding columns
how to retreive data dynamically from mysql to drop down list
how to retreive data dynamically from mysql to drop down list   sir, i created a table in mysql and i inserted some values into the table through fron end using jsp , after storing the data successfully .i want to retrieve
struts hibenate integration - Hibernate
struts hibenate integration  struts hibernate integration
EAI - Service Oriented Architecture,EAI Architecture,Enterprise Application Integration,Enterprise Application Integration EAI
there is a hub that acts as a central point through which all the integration... skmota@yahoo.com Summary: This article explains about various integration terminologies, its usage and relationships to Enterprise Application Integration (EAI
store data from a variable in mysql?
store data from a variable in mysql?  sir last time asked you tell me how to retrieve data from a database mysql and store it in an int variable... of the calculation from an int variable into mysql in a new table of database. how
jfreechart display from access database data.
jfreechart display from access database data.  I have made a database... to retrieve the data from the access database using prepared statement and then display... is to be done in a servlet.. Note that it is a access made database. How can I
retrieve data from mysql database
retrieve data from mysql database  hi am not familiar in php.....even... selected value on combobox which is to be retrieve the relevant data from mysql...;/html> retcombosearch.php form is <?php mysql_connect ("localhost
Developing Struts Hibernate and Spring Based Login/Registration Application
application based on Struts, Hibernate and Spring Framework. We will be using... frameworks e.g. Struts, Hibernate and Spring.   About this Login... application that can be used later in any big Struts Hibernate and Spring
Purge Data from Mysql tables
Purge Data from Mysql tables  Hi, i have to write a mysql procedure to purge data from tables. but written procedure clear entire tables data. Please give me the solution for purging data. CREATE DEFINER=`root`@`localhost
ACCESS DATABASE FROM HTML
ACCESS DATABASE FROM HTML  I want to access sql 2008 database in html page without help of ADODB connection.. because if access through ADODB means there is a security problem. so, Access database in html page(client side
access image from ajax store in mysql using jsp
access image from ajax store in mysql using jsp  access image from ajax store in mysql using jsp (code to access image captured by camera and store in mysql
Data is not inserting correctly in mysql database.
Data is not inserting correctly in mysql database.  Hello Sir, below is my code to insert data into database by list iteration through for loop but it is not getting inserted ..it is taking only one value
how to read data from excel file through browse and insert into oracle database using jsp or oracle???
how to read data from excel file through browse and insert into oracle database... a browse button which can upload a excelfile and after uploading the data should..., Please go through the following links may this will be helpful for you. However
php import data from excel to mysql
php import data from excel to mysql  php import data from excel to mysql
Simplified Application Development with Struts, Hibernate and Spring
Simplified Application Development with Struts, Hibernate and Spring... knowledge about different frame works like Hibernate, Spring and Struts, which... source projects such as Spring, Hibernate and Struts and their use in J2EE
display data from a table in Access Database in a HTML page
display data from a table in Access Database in a HTML page  how to display data from a table in Access Database in a HTML page in a Java Program
design chart takes data from database and through jsp page
design chart takes data from database and through jsp page  how can I design chart takes data from database and through in jsp page

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.