Hibernate

adplus-dvertising
Inserting Data into One or More than One table in the database Using Hibernate and JSP
Previous Home Next

Here we will discuss that how to work with the struts and hibernate. We can work with the hibernate and struts together. One example we will discuss here below. We will use here NetBenas and Mysql with Hibernate. We follow the some basic step that are given below:

Step 1. First of all we need to create a web application for this we go in the file menu wizard -> click on the new Project -> click on java web and then java web application -> put the name on the required field -> select the server which we want to use here to build the project -> first select to hibernate and then select to struts framework. (if we do not add the struts framework then we can use this by the adding jar file directly) -> now click on finish.

hibernate.cfg.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate 
Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_pro</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
  </session-factory>
</hibernate-configuration>

Step 2. Now we create a table on the given database which we select on the configuration file.


create table AddStruts
(
id int not null auto_increment primary key,
fname varchar(50),
lname varchar(50),
mob varchar(50),
address varchar(50),
state varchar(50),
city varchar(50),
pin int(6)
)

Step 3. Now we need to create a jsp page click on file menu wizard -> new file -> web and jsp -> put the name on the required field -> click on finish.


<%@taglib uri="/struts-tags" prefix="s" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title><s:text name="Welcome Page"/></title>
    </head>
    <body>
        <s:form action="insert" method="post">
            <s:textfield label="First Name" name="fname"/>
            <s:textfield label="Last Name" name="lname"/>
            <s:textfield label="Address" name="address"/>
            <s:textfield label="State" name="state"/>
            <s:textfield label="City" name="city"/>
            <s:textfield label="Pin Code" name="pin"/>
            <s:submit value="Submit"/>
        </s:form>
    </body>
</html>

Step 4. Now we need to create a package to store the action and pojo class. for this we need to go in the file menu wizard and -> click on new file -> search java and the opposite side click on package -> type the name of the package which we want -> click on finish.

Step 5. Now we need to create reverse eng file . Go in the file menu wizard -> new file click on -> hibernate and reverse eng file -> select table which we created in the database -> click on finsih.


 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate 
Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="hibernate_pro"/>
  <table-filter match-name="AddStruts"/>
</hibernate-reverse-engineering>

Step 5. Now create a pojo class on the created package. click on file menu wizard -> new file -> hibernate -> hibernate pojo class -> select package -> click on finish.

AddStrust.hbm.xml


 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 26 Dec, 2014 11:55:13 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.AddStruts" table="AddStruts" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="fname" type="string">
            <column name="fname" length="50" />
        </property>
        <property name="lname" type="string">
            <column name="lname" length="50" />
        </property>
        <property name="mob" type="string">
            <column name="mob" length="50" />
        </property>
        <property name="address" type="string">
            <column name="address" length="50" />
        </property>
        <property name="state" type="string">
            <column name="state" length="50" />
        </property>
        <property name="city" type="string">
            <column name="city" length="50" />
        </property>
        <property name="pin" type="java.lang.Integer">
            <column name="pin" />
        </property>
    </class>
</hibernate-mapping>

AddStrust.java


package r4r;
public class AddStruts  implements java.io.Serializable {
     private Integer id;
     private String fname;
     private String lname;
     private String mob;
     private String address;
     private String state;
     private String city;
     private Integer pin;

    public AddStruts() {
    }

    public AddStruts(String fname, String lname, String mob, String address, String state, String city, Integer pin) {
       this.fname = fname;
       this.lname = lname;
       this.mob = mob;
       this.address = address;
       this.state = state;
       this.city = city;
       this.pin = pin;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFname() {
        return this.fname;
    }
    
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return this.lname;
    }
    
    public void setLname(String lname) {
        this.lname = lname;
    }
    public String getMob() {
        return this.mob;
    }
    
    public void setMob(String mob) {
        this.mob = mob;
    }
    public String getAddress() {
        return this.address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    public String getState() {
        return this.state;
    }
    
    public void setState(String state) {
        this.state = state;
    }
    public String getCity() {
        return this.city;
    }
    
    public void setCity(String city) {
        this.city = city;
    }
    public Integer getPin() {
        return this.pin;
    }
    
    public void setPin(Integer pin) {
        this.pin = pin;
    }

}

Step 6. Now we need to create a java class for the creating the session with the hibernate. go in file menu wizard -> click on new file -> java -> java class -> put the name on the required field -> select to package -> finish.


 package r4r;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlug 
{
	private static SessionFactory factory = getSessionFactory();
	
	public static synchronized SessionFactory getSessionFactory() 
	{	
	try {	    
	
	    Configuration cfg = new Configuration();
	    cfg.configure("hibernate.cfg.xml"); 
	
	    SessionFactory sessionFactory = cfg.buildSessionFactory();
	    System.out.println(" ----------   Factory Object Created  ------------");
	    return sessionFactory;
						    
 
	     }             catch (Throwable ex) {
	    System.err.println("Initial SessionFactory creation failed." + ex);
	     throw new ExceptionInInitializerError(ex);
	      }
	  }
	
	public static SessionFactory getFactory() {
	return factory;
	}
	
}

Step 6. Now we need to create a action class. go in file menu wizard -> click on new file -> java -> java class -> put the name on the required field -> select to package -> finish.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package R4R_Dao;

/**
 *
 * @author sarvesh
 */
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import R4R.AddStruts;

public class AddData extends ActionSupport implements ModelDriven, Preparable {
 
	    AddStruts employee;
	    SessionFactory sessionFactory = null;
	    Session session = null;
	 
            @Override
	    public String execute() {
	        try {
	            sessionFactory = new Configuration().configure().buildSessionFactory();
	            session = sessionFactory.openSession();
	            Transaction transaction = session.beginTransaction();
	            session.saveOrUpdate(employee);
	            transaction .commit();
	            System.out.println("Record Inserted Successfully");
	        } catch (HibernateException hibernateException) {
	            System.out.println(hibernateException.getMessage());
	            session.close();
	            return "ERROR";
	        }
	        return "SUCCESS";
	    }
	 
	    @Override
	    public AddStruts getModel() {
	        return employee;
	    }
	    @Override
	    public void prepare() throws Exception {
	        employee = new AddStruts();
	    }
	}

Step 7. Now we need to modified to the struts.xml file for making the action.


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
                <action name="insert" class="R4R_Dao.AddData">
	            <result name="SUCCESS">/Success.jsp</result>
                    
	             <result name="ERROR">/Error.jsp</result>
	        </action>
    </package>
</struts>

Step 8. Now we need some another jsp file for performing the action so we need to create as we already to create a jsp page so follow that step.


<%@page contentType="text/html" pageEncoding="UTF-8" import="R4R_Dao.AddData"%>
	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	   "http://www.w3.org/TR/html4/loose.dtd">
	<%@taglib prefix="s"  uri="/struts-tags"%>
	<html>
	    <head>
	        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	        <title>JSP Page</title>
    </head>
	    <body><center>
	            <br>  <br>  <br>  <br>
	            <h1 style="color:chocolate"> <s:property value="name"/> registered successfully !!</h1>
	               </center>
	           </body>
	</html>

Step 9. Now we will run the project. so right click on the project node -> click on clean and build -> then run.

Step 10. Now check to the database table.

Previous Home Next