Hibernate

adplus-dvertising
First Application In Hibernate
Previous Home Next

Creation a web application using servlet in hibernate

Before creating a web applcation we need to install NetBeans IDE and also need to install Hibernate Frame work with NetBeans and MySQL also required. Now open the MySql and create a own database for Hibernate frame work .

Type these command in MySQL Editor:

create database hibernate_pro;

With the help of this command we can create a data base in the database to save the own data. DataBase is that area where we can put our data like as tables,procedures. etc

use hibernate_pro;

create table person


create table person
          (

id int(4) auto_increment primary key,

first_name varhcar(30),

last_name varchar(30),

age varchar(30),

profession varchar(50)

);

By this command we can create table which has id, first_name, last_name,age, profession are the field of the table in which we want to insert the data. In the table id show the unique quality of the table person. when we take the data type varchar then we are able to store any character value or any integer value in the data base.

select * from person;

We can see the data in the table by this command. This command will show the all data in the database. Here select is used to fetch the table from the data base.

Creation a web application in NetBean IDE:

Now Open the NetBeans IDE open File Menu Wizard -> New Project Go-> File Menu Wizard -> Select to New Project -> Select Java web -> and also select web application -> click next ->(As Given in above image) Write the project name HibernateWeb1 then click next->(As Given in above image) Here select server on which you want to build the project -> then Next (As Given in above image) Search the Hibernate Framework and mark on the hibernate and when mark will be on the one tab will open in the same page select to new connection to make the connection with database -> New Connection Wizard (As Given in above image) Now you will see in your Netbeasn IDE acording the given image and ->select according the image and click next -> and then finish. (As Given in Below Mentioned image)

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?zeroDateTimeBehavior=convertToNull</property>

    <property name="hibernate.connection.username">root</property>

    <property name="hibernate.connection.password">root</property>

  </session-factory>

</hibernate-configuration>

In the above code we can see the some critical parts which should be always remember. When we make the connection with the database and NetBeans Generate auto hibernate.cfg.xml file. In that file we see our database host name and port name alse.

If we given the password in the database then we see the user name and password in the above mentioned code.

Till then we don't create the POJO class we can't see the mapping file with the database name and file name also.

If all thing are completed then our project created correctly.

Creation of the Index page

As we shown in the below image we can create a index page. It work to making the input source we can say that it work as the designing page of ours. Without designing page we can't nothing in any platform. In the designing page we perform the action via our action strategies.

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 >
        <form action="MyServlet1" method="post">
            First Name      <input type="text" name="first_name" value="" />
            Last Name       <input type="text" name="last_name" value="" />
            Age             <select name="age">
                            <option>--Select 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 Profession--</option>
                            <option>Manager</option>
                            <option>Clerk</option>
                            <option>Teacher</option>
                            </select>
            <input type="submit" value="Sign In" />
        </form>
    </body>
</html>

Creating the servlet

Now we need a servlet file for making connection for this we need to go in the file menu select -> new file -> web -> servlet -


package mypack;

import java.io.IOException;

import java.io.PringWriter;

import java.servlet.ServletException;

import java.servlet.HttpServlet;

import java.servlet.http.HttpServletRequest;

import java.servlet.http.HttpServletResponse;



public class MyServlet1 extends HttpServlet

{



public void processRequest(HttpServletRequest request, HttpServletResponse response)

	throws ServletException, IOException

	  {

 response.setContentType("text/html;charset=UTF-8");


 String first_name,last_name,age,profession;

first_name = request.getParameter("first_name");

last_name = request.getParameter("last_name");

age = request.getParameter("age");

profession = request.getParameter("profession");

SessionFactory sf = new Configuration().configure().buildSessionFactory();

Session s = sf.openSession();

Transaction tx = null;

try

  {

	tx = s.beginTransaction();

	Person a = new Person(first_name,last_name,age,profession);

	s.save(a);

	tx.commit();

  }catch(Exception e)

     {

       if(tx!=null) tx.rollback();

     }

    finally

       {

          if(s!=null)

            {

               s.close();

            }

        }


try(PrintWriter out = response.getWriter())

  {

 out.println("<!DOCTYPE=html>");

 out.println("<html>");

 out.println("<head>");

 out.println("<title>Welcome</title>");

 out.println("</head>");

 out.println("<body>");

 out.println("<h1>Servlet at  my request at "+ first_name +"</h1>");

	out.println("</body>");

	out.println("<html>");

 }

	}

Creation ReverseEngineering File

When we have make the connection with the database then we can easily create hibernate.reveng.xml file. For the creating the hibernate.reveng.xml we need to follow some basic step those are below: Go in File Menu Wizard -> New File -> Find the Hibernate and then click on hibernate.reveng.xml -> Next In the hibernate.reveng.xml file default name shown in below image and press Next. Here we can put the hibernate.reveng.xml file where we want to put. But path will be shown (as in figure ) by default. So No need to change. In Below image if our database connection was correct then we can find that table which we have created in the database. In image which is highlighted table name is person. Select it. Click on add as in below image and click on finish. As in below image when we click on the finish at that time hibernate.reveng.xml will be created in the default package.


<?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="person"/>

</hibernate-reverse-engineering>

Highlighted code line of hibernate.reverse.xml is that database name and table name.

POJO Creation

Before creating the POJO class we need to create the hibernate.revenge.xml and hibernate.cfg.xml. If we done it then we can create the POJO class. Because POJO class when created till then we don't have the both xml file. We can create the POJO class for this we need to Go in File Menu Wizard-> select New file wizard -> search Hibernate and click Hibernate Mapping POJO class -> as shown in image and then press Next If we have both xml file (hibernate.cfg.xml and hibernate.revenge.xml) then we can create the POJO Class. It is mendatory. Mark on the JDK 5 feature. Always remember that POJO class having a perticular package to put. So we write the package name in package name option. and then Finish. When we click on the Finish that time two file will be create person.hbm.xml and person.java as shown in the image.


<?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 18 Oct, 2014 3:14:58 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="mypack.Person" table="person" 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="40" />

        </property>

        <property name="lastName" type="string">

            <column name="last_name" length="40" />

        </property>

        <property name="age" type="string">

            <column name="age" length="20" />

        </property>

        <property name="profession" type="string">

            <column name="profession" length="15" />

        </property>

    </class>

</hibernate-mapping>


 package mypack;

// Generated 18 Oct, 2014 3:14:58 PM by Hibernate Tools 4.3.1

/**

 * Person generated by hbm2java

 */

public class Person  implements java.io.Serializable {

     private Integer id;

     private String firstName;

     private String lastName;

     private String age;

     private String profession;

    public Person() {

    }

    public Person(String firstName, String lastName, String age, String profession) {

       this.firstName = firstName;

       this.lastName = lastName;

       this.age = age;

       this.profession = profession;

    }

    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;

    }

}

Output of the Project in the Browser after the Building of the project on the server:

When we have completed all work like as reverse engineering ,pojo class and servlet file then we can build the project. You can select the project node for build or you can build to selecting file through index.jsp file right click on the file and select the run the project in menu option. then your project will build and run. As given in the images.

Output of the Data Base When we have inserted the data by the browse:

When we insert the required value in the required field and then submit the value goes into the database. So for the see this we have to follow the same required. We need to type the command in the editor of my sql then we found the last entry at the time when we inserted the value by the browser. select * from person; select work for fetching the table from the database. In the hilighted row shows that in this row has a new entry which inserted by the browser.

Previous Home Next