how to save data using hibernate

In this post i explain how to insert data into MySQL database using Hibernate with the help of NetBeans IDE.
First you need to create a database and a table in the MySQL database. While creating the table keep in mind that, the table must contain a primary key field. I use the following query for create the table.
 create table test_table (id int not null primary key auto_increment,name varchar(50), email varchar(50));  
Ads by Google


Now you need to follow the steps given bellow.

Step  1 :
             Open up  the NetBeans IDE.
Step  2 :
             Go to the services and expand the database.
example in hibernate
Step 3:
           Now right click MySQL server and choose connect. 
save data using hibernate in mysql
Step 4:
          Now you need to enter your MySQL username and password and choose the database to which you want to insert data. Right click the database and choose connect. 
mysql database with hibernate
Step 5:
          Create a new Web Application and choose the hibernate framework and choose the database connection.
hibernate data saving example
Step 6:
         Right click the project name  from the other option, choose Hibernate and from the hibernate folder choose the hibernate reverse engineering wizard. 
hibernate netbeans
Step 7:
Click next and choose the table / tables and click the add button and finally click finish. 
hibernate simple data saving example

Now you got your hibernate reverse engineering xml file. 

Step 8:
Right click the project, choose other and from hibernate folder select the "Hibernate mapping files and POJOs" from database.
data saving in java

You need to provide a package name and click finish. Now you got your hibernate mapping xml file and the POJO class file as shown bellow. 
what is hibernate

Step 9 :
Create a form in your index.jsp as shown bellow.
  <form action="TestServlet">  
Name :<input type="text" name="name"/>
Email :<input type="text" name="email" />
<input type="submit" value="SAVE" />
</form>

Step 10:
Create a new servlet and add the following code segment in processRequest method as shown bellow.
    String name,email;  
name = request.getParameter("name");
email = request.getParameter("email");
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session s = sf.openSession();
Transaction tr = s.beginTransaction();
TestTable t = new TestTable(name, email);
s.save(t);
tr.commit();
s.close();

Now run the index.jsp file and check data in your database table.

Watch Video Tutorial of this Topic