Inserting Data into More than One table in the database with Hibernate Using Servlet and JSP by R4R Team

For creating the web application we are using NetBeans and MySQL server and appache tomcat for building the application. As we have discussed in our last application. In the last application we insert data into one table of the database but here in this application we will insert data into more than one application. So to create this application we need to go through some basic step to create application as we done in last application. This application will same as the last application.

Step 1. Create a database in MySQL database.


(q) create database hibernate_pro;
(r) use hibernate_pro;

Step 2. First of all we need to create three table like as in MySQL

Which code we seeing in the DataBase for table creation that is given below:

(1) create table Student_01
      (
         id int primary key not null auto_increment,
         first_name varchar(50),
         last_name varchar(50),
         age varchar(50),
         profession varchar(50),
         sex varchar(50),
         address varchar(50)
      )

(2) create table Student_address
      (
        id int primary key not null auto_increment,
        address varchar(50)
      )

(3) create table Student_Sexual_Information
      (
        id int primary key not null auto_increment,
        age varchar(50),
        sex varchar(50)
      )

Step 3. check the each table is any data is availabe in the table or not so use the following code:

Below code is given in the image:

(1) select * from Student;
(2) select * from Student_Address;
(3) select * from Student_Sexual_Information;

Step 4. Create a Web Application. Go in File Menu Wizard -> click on new project -> type the name on the given place and next press -> select server apache tomcat and next -> click on hibernate and database hibernate_pro and then finish.

given above code hibernate.cfg.xml after creating pojo class:

<?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>
    <mapping resource="r4r/StudentAddress.hbm.xml"/>
    <mapping resource="r4r/StudentSexualInformation.hbm.xml"/>
    <mapping resource="r4r/Student01.hbm.xml"/>
    <mapping resource="r4r/ContactInformation.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Step 5. Create a file by which we store the value into the database. click on File Menu Wizard -> click on new file wizard -> click on web and than jsp ->type the file name on the given place 'index' and finish .

above code is given here of index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body><pre><h3>
        <form action="InsertData" method="post">
            First Name :        <input type="text" name="fname"/>
             
             Last Name :        <input type="text" name="lname"/>
            
                    Age:        <select name="age">
                                <option>--Select Your Age --</option>
                                <option>10 to 20</option>
                                <option>20 to 30</option>
                                <option>30 to 40</option>
                                <option>40 to above</option>
                                </select>                 
            
             Profession:        <select name="profession">
                                <option>--Select Your Profession--</option>
                                <option>Student</option>
                                <option>Govt Servent</option>
                                <option>Doctor</option>
                                <option>Professor</option>
                                </select>
                    
                    Sex:        <select name="sex">
                                <option>--Select Sex--</option>
                                <option>Male</option>
                                <option>Female</option>
                                </select>
               
                Address:        <input type="text" name="address"/>
                
                Mobile          <input type="text" name="mobile"/>
                    
                                <input type="submit" value="Submit"/>
        </form>
                        <button type="submit"><a href="hi.jsp">hi</a></button> 
    </body>
</html>

Step 6. create a reverse engineering file. click on file menu wizard -> new file -> click on hibernate and then reverse engineering file -> select the table and add -> click on finish. (it will live in the default package)

hibernate.revenge file above code:

<?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="Student_01"/>
  <table-filter match-name="Student_address"/>
  <table-filter match-name="Contact_Information"/>
  <table-filter match-name="Student_Sexual_Information"/>
</hibernate-reverse-engineering>

Step 7. create a package. click on File Menu Wizard -> new file -> java -> click on package -> type the package name which you want -> finish.

Step 8. Now create a POJO class. for this go in file menu wizard -> new file -> click on hibernate on left hand tab -> click on hibernate pojo class -> select to package which you have created click on finish.

Above given code is pasted here StudentSexualInformation.java:

package r4r;
// Generated 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1
/**
 * StudentSexualInformation generated by hbm2java
 */
public class StudentSexualInformation  implements java.io.Serializable {

     private Integer id;
     private String age;
     private String sex;

    public StudentSexualInformation() {
    }

    public StudentSexualInformation(String age, String sex) {
       this.age = age;
       this.sex = sex;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAge() {
        return this.age;
    }
    
    public void setAge(String age) {
        this.age = age;
    }
    public String getSex() {
        return this.sex;
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }

}

Above given code is pasted here of StudentSexualInformation.hbm

<?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 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.StudentSexualInformation" table="Student_Sexual_Information" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="age" type="string">
            <column name="age" length="50" />
        </property>
        <property name="sex" type="string">
            <column name="sex" length="50" />
        </property>
    </class>
</hibernate-mapping>

Above given code is pasted here of StudentAddress.java:

package r4r;
// Generated 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1
/**
 * StudentAddress generated by hbm2java
 */
public class StudentAddress  implements java.io.Serializable {
     private Integer id;
     private String address;

    public StudentAddress() {
    }

    public StudentAddress(String address) {
       this.address = address;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAddress() {
        return this.address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }

}

Above given code is pasted here of StudentAddress.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 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.StudentAddress" table="Student_address" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="address" type="string">
            <column name="address" length="50" />
        </property>
    </class>
</hibernate-mapping>

Above given here pasted of Student01.java:

package r4r;
// Generated 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1
/**
 * Student01 generated by hbm2java
 */
public class Student01  implements java.io.Serializable {
     private Integer id;
     private String firstName;
     private String lastName;
     private String age;
     private String profession;
     private String sex;
     private String address;

    public Student01() {
    }

    public Student01(String firstName, String lastName, String age, String profession, String sex, String address) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.age = age;
       this.profession = profession;
       this.sex = sex;
       this.address = address;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return this.firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return this.lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getAge() {
        return this.age;
    }
    
    public void setAge(String age) {
        this.age = age;
    }
    public String getProfession() {
        return this.profession;
    }
    
    public void setProfession(String profession) {
        this.profession = profession;
    }
    public String getSex() {
        return this.sex;
    }
    
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getAddress() {
        return this.address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }

}

Above code is given here of Student01.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 2 Dec, 2014 7:48:56 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.Student01" table="Student_01" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="50" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="50" />
        </property>
        <property name="age" type="string">
            <column name="age" length="50" />
        </property>
        <property name="profession" type="string">
            <column name="profession" length="50" />
        </property>
        <property name="sex" type="string">
            <column name="sex" length="50" />
        </property>
        <property name="address" type="string">
            <column name="address" length="50" />
        </property>
    </class>
</hibernate-mapping>

Step 9. create a servlet file for action. click on file menu wizard -> new file -> click on servlet -> type the name on the given place, select package and click on next -> mark on the add information button -> click on finish.

Step 10. edit the code and put the action to inserting the value in the database.

Above Selected code is pasted here to understand the what and how to perform the action through servlet (InsertData.java)

package r4r;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertData extends HttpServlet 
{
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String fname,lname,age,profession,sex;
        String address,mob;
       // int mob = Integer.parseInt(request.getParameter("mobile"));
        fname = request.getParameter("fname");
        lname = request.getParameter("lname");
        age = request.getParameter("age");
        profession = request.getParameter("profession");
        sex = request.getParameter("sex");
        address = request.getParameter("address");
       mob = request.getParameter("mobile");
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();
        Student01 s1 = new Student01(fname, lname, age, profession, sex, age);
        StudentAddress s2 = new StudentAddress(address);
        StudentSexualInformation s3 = new StudentSexualInformation(age, sex);
        
        ContactInformation s4 = new ContactInformation(Integer.parseInt(request.getParameter(mob)));
        
        s.save(s1);
        s.save(s2);
        s.save(s3);
        s.save(s4);
        tr.commit();
        s.close();
        
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet InsertData</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Welcome Mr. " + fname + " "+lname+" in our java programming</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

}

Step 11. Attatch the database jar file.

Step 12. build the project.

Step 13. Run the project.

Step 14. put data on the required field of the jsp page and then submit.

Step 15. Now check the databaset each table by typing such these command.

(1) select * from Student;
(2) select * from Student_Address;
(3) select * from Student_Sexual_Information;



Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!