Here, we are going to create a web application with hibernate. For creating the web application, we are using JSP for presentation logic, Bean class for representing data and DAO class for database codes.
NOTE : Above script is written for SQL Server, you can change accordingly for different DB.
put this file under root folder.
@Entity annotation marks this class as an entity.
@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.
@Id annotation marks the identifier for this entity.
@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.
NEXT READ Hibernate one to one example with annotation code
Follow us on social media to get latest tutorials, tips and tricks on Hibernate.
Please share us on social media if you like the tutorial.
Example to create web application using hibernate
Creating Database
Before we start lets create a simple database and table to apply hibernate operations on. Copy and Paste the following sql query in your query editor and execute.CREATE table STUDENT (ID bigint identity, rollno varchar(20), firstname varchar(50), lastname varchar(50), course varchar(50), address varchar(100))
NOTE : Above script is written for SQL Server, you can change accordingly for different DB.
Adding Hibernate Jars
Download latest Hibernate jars from here http://hibernate.org/ and add to your classpath.Add hibernate.cfg.xml
It is a configuration file, containing informations about the database and mapping file.put this file under root folder.
<?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.connection.driver_class">net.sourceforge.jtds.jdbc.Driver</property> <property name="hibernate.connection.password">yourdbpassword</property> <property name="hibernate.connection.url">jdbc:jtds:sqlserver://localhost:1433/yourdbname</property> <property name="hibernate.connection.username">yourdbusername</property> <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="connection.pool_size">1</property> <property name="hbm2ddl.auto">create</property> <mapping class="com.tutorialsdesk.hibernate.bean.Student"/> </session-factory> </hibernate-configuration>
Adding Hibernate Utils class
This is a simple java class with a static method, we will use this class to get a session instance of hibernate session factory class.package com.tutorialsdesk.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } }
Adding bean class file
This is a simple pojo consisting of an Student object, we will map this class to relational database using hibernate utilities.@Entity annotation marks this class as an entity.
@Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name bydefault.
@Id annotation marks the identifier for this entity.
@Column annotation specifies the details of the column for this property or field. If @Column annotation is not specified, property name will be used as the column name bydefault.
package com.tutorialsdesk.hibernate.bean; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="STUDENT") public class Student { @Id @GeneratedValue private int id; @Column(name="rollno") private String rollno; @Column(name="firstname") private String firstname; @Column(name="lastname") private String lastname; @Column(name="course") private String course; @Column(name="address") private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRollno() { return rollno; } public void setRollno(String rollno) { this.rollno = rollno; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getCourse() { return course; } public void setCourse(String course) { this.course = course; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
StudentDao.java
This is simple java class containing main method to start execution, see the implementation to identify hibernate working in create, retrieve, update and delete operations.package com.tutorialsdesk.hibernate; import java.util.ArrayList; import org.hibernate.*; import com.tutorialsdesk.hibernate.bean.Student; public class StudentDao { public static void saveUser(Student student) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(student); session.getTransaction().commit(); } public void updateUser(Student student) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.merge(student); session.getTransaction().commit(); } public void deleteUser(Student student) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.delete(student); session.getTransaction().commit(); } public void getUser() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); ArrayList<Student> list = (ArrayList<Student>) session.createQuery("from Student").list(); if (list != null) { for (int i = 0; i < list.size(); i++) { System.out.println("User ID : " + list.get(i).getId()); System.out.println("User First Name : "+ list.get(i).getFirstname()); System.out.println("User Last Name : "+ list.get(i).getLastname()); System.out.println("User Roll No : " + list.get(i).getRollno()); System.out.println("User Address : " + list.get(i).getCourse()); } } session.getTransaction().commit(); } }
Add index.jsp
This page gets input from the user and sends it to the register.jsp file using post method.<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="register.jsp" method="post"> Roll Number:<input type="text" name="rollno"/><br><br/> First Name:<input type="text" name="firstname"/><br><br/> Last Name:<input type="text" name="lastname"/><br><br/> Course:<input type="text" name="course"/><br><br/> Address:<input type="text" name="address"/><br><br/> <input type="submit" value="register"/>" </form> </body> </html>
Add register.jsp
This file gets all request parameters and stores this information into an object of User class. Further, it calls the register method of UserDao class passing the User class object.<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <%@page import="com.tutorialsdesk.hibernate.StudentDao"%> <jsp:useBean id="obj" class="com.tutorialsdesk.hibernate.bean.Student"> </jsp:useBean> <jsp:setProperty property="*" name="obj"/> <% StudentDao.saveUser(obj); out.print("You are successfully registered"); %> </body> </html>
Final Project Structure
Your final Project Structure under webapps folder will be as followsNEXT READ Hibernate one to one example with annotation code
Follow us on social media to get latest tutorials, tips and tricks on Hibernate.
Please share us on social media if you like the tutorial.
Blogger Comment
Facebook Comment