Hibernate Web Application with Example

Let us create a hibernate web Application. Here we need JSP file for presentation.

There are steps given below for the web app creation.

index.jsp

This page will show a registration form. It takes the input from the form and sends it to the register.jsp page.

 
  Name:

  Mobile No:

Password:

  Email ID:

   
 

register.jsp

The register.jsp file will get all the information from index.jsp and stores it in the object (s) of Student class.

 <%@pageimport="com.hibernate.webap.StudentDao"%>  
   
   
   
   
 <%  
 int i=StudentDao.register(s);  
 if(i>0)  
 out.print("Registration is successfull");  
 %>   

Student.java

It is a bean class. All the variables of bean class are set as private with public setter and getter methods.

 public class Student {
private int id,phnno;
private String name,email,password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPhnno() {
return phnno;
}
public void setPhnno(int phnno) {
this.phnno = phnno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} 

StudentDao.java

It contains the method to store the object of Student class.

import org.hibernate.cfg.Configuration;
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
    
public class StudentDao {    
     
public static int register(Student student){    
int i=0;    
   
Configuration cfg= new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory= cfg.buildSessionFactory();
Session session = factory.openSession();  
session.beginTransaction(); 
  
i=(Integer)session.save(student);    
   
session.getTransaction().commit();    
session.close();    
return i;    
       }    
  }     

student.hbm.xml

It maps the object of Student class with the database table.

   
 
http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
   
   
  
  
  
  
  
  

  
  
        

hibernate.cfg.xml

It contains information about the mapping file and relational database.

   
  

  
  

update  
org.hibernate.dialect
.MySQL5Dialect
com.mysql.
jdbc.Driver
jdbc:mysql://
localhost:3306/test2
root                        
root                        
 
 
  
  
                                                    

Output



ADVERTISEMENT
ADVERTISEMENT