Skip to main content

HIBERNATE (WITH @NNOTATION) IN WEB APPLICATION



In this post, am going to cover the basic way to setup the hibernate environment in eclipse to do a simple insert operation in mysql database and this post is meant for beginners who doesn't know about hibernate configurations coz am similar kind. I can't post this in codeproject coz it requires some more documentation so if you want the project files message me in G+ I will post you the project files.

Folder structure & Libraries required:

 It gives clear details about file placement and libraries required.

Application setup:

·         JDK 6
·         Eclipse Juno
·         Tomcat 7.0
·         MySQL 5.1
·         Supporting libraries for hibernate.

Steps:

·         Creating project in Eclipse.
·         Loading JARs.
·         Configuring and Adding classes.
·         Run.

Create Project in Eclipse:

·         Open – Eclipse > Go to > File > New > Dynamic web project.

Loading JARs

Add all the required JARs in in the folder lib which resides inside web content > web-inf.
Location: ‘Projectname/WebContent/WEB-INF/lib ’.
After adding those JARs into the lib directory need to include them into project.
·         Right click on project > select Build path > Configuration Build Path.
·         Select Java Build path from sidebar menu and select Libraries tab > select Add JARs.

Configuring and Adding classes:

Add ‘hibernate.cfg.xml’ in the location ‘Projectname/JavaResources/src/’ and load the below code to it.

 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">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:5050/dbName</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">password</property>
        <property name="connection.pool_size">10</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="modal.Student" />
        <mapping class="modal.Department" />
    </session-factory>
</hibernate-configuration>

Add the below code in web.xml


<servlet>
    <description></description>
    <display-name>HibernateController</display-name>
    <servlet-name>HibernateController</servlet-name>
    <servlet-class>service.HibernateController</servlet-class>
 </servlet>
 <servlet-mapping>
    <servlet-name>HibernateController</servlet-name>
    <url-pattern>*.do</url-pattern>
 </servlet-mapping>

Class Creation

Create util package:

Create package in the name “util” inside “src” folder > create the class HibernateUtil” > Load the below code into the class created.
package util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {
       private static final SessionFactory sessionFactory;
       static {
              try {
                     sessionFactory = new AnnotationConfiguration().configure()
                                  .buildSessionFactory();
              } catch (Throwable ex) {
                     throw new ExceptionInInitializerError(ex);
              }
       }

       public static SessionFactory getSessionFactory() {
              return sessionFactory;
       }
}

Create model package:

Create package in the name “model” inside “src” folder > create the entity classes here in this sample I have created to classes “Department” and “student” and load the below code into the classes created respectively.
package modal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Department")
public class Department {
       int deptID;
       String deptName;
       String HOD;

       public Department() {
       }

       public Department(String deptName,String HOD) {
              this.deptName = deptName;
              this.HOD=HOD;
       }

       @Id
       @GeneratedValue
       @Column(name="Dept_ID")
       public int getDeptID() {
              return deptID;
       }
       public void setDeptID(int deptID) {
              this.deptID = deptID;
       }

       @Column(name="Dept_Name", nullable=false)
       public String getDeptName() {
              return deptName;
       }
       public void setDeptName(String deptName) {
              this.deptName = deptName;
       }

       @Column(name="HOD", nullable=false)
       public String getHOD() {
              return HOD;
       }
       public void setHOD(String hOD) {
              HOD = hOD;
       }
}
package modal;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;

@Entity
@Table(name="Student")
public class Student {
       private long rollNo;
       private String name;
       private Set dept= new HashSet(0);

       public Student() {
       }

       public Student(String name) {
              this.name = name;
       }

       public Student(String name, Set dept) {
              this.name = name;
              this.dept = dept;
       }

       @Id
       @GeneratedValue
       @Column(name="RollNo")
       public long getRollNo() {
              return rollNo;
       }
       public void setRollNo(long rollNo) {
              this.rollNo = rollNo;
       }

       @Column(name="Name", nullable=false)
       public String getName() {
              return name;
       }
       public void setName(String name) {
              this.name = name;
       }

@ManyToMany(cascade = CascadeType.ALL)
       @JoinTable(name = "STUDENT_COURSE", joinColumns = { @JoinColumn(name = "STUDENT_ID") }, inverseJoinColumns = { @JoinColumn(name = "COURSE_ID") })
       public Set getCourses() {
              return this.dept;
       }

       public void setCourses(Set dept) {
              this.dept = dept;
       }
}

Create service package:

Create package in the name “service” inside “src” folder > create the servlet “HibernateController” > Load the below code.
package service;

import java.util.HashSet;
import java.util.Set;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import modal.Department;
import modal.Student;
import util.HibernateUtil;

/**
 * Servlet implementation class HibernateController
 */
public class HibernateController extends HttpServlet {
       private static final long serialVersionUID = 1L;
/**
        * @see HttpServlet#HttpServlet()
        */
       public HibernateController() {
              super();


              // TODO Auto-generated constructor stub
       }

       /**
        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
        */
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub

       }

       /**
        * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
        */
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              Session session = HibernateUtil.getSessionFactory().openSession();
              Transaction transaction = null;
              try {
                     transaction = session.beginTransaction();

                     Set dept = new HashSet();
                     dept.add(new Department("IT","Sreekanth"));
                     dept.add(new Department("Admin","Senthil"));

                     Student student1 = new Student("Sahana", dept);
                     Student student2 = new Student("Reshma", dept);
                     session.save(student1);
                     session.save(student2);

                     transaction.commit();
              } catch (HibernateException e) {
                     transaction.rollback();

              } finally {
                     session.close();
              }
              response.getWriter().println("Created");
       }

}

Create an index.jsp:

For testing we are just going to create a sample a page and place button in that. On click of the button we are just going to trigger the event to do the hibernate functionalities.
<%@ 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>Home Page</title>
</head>
<body>
<form action="HibernateController.do" method="post">
<button name="btnSubmit" type="submit" value="Click"></button>
</form>
</body>
</html>

You gone through everything, gr8!!! Post your feedback so that I could improvise this post to help beginners like me :) :)



Comments

Popular posts from this blog

Creating multi module project with maven

Creating my first multi module project with maven I got a superb step by step article for maven project creation in eclipse while googling. This article is good for beginners like me :) , no need do too many things, just follow the steps at the end you will see “Hello World” in the browser. Check the below link for the wonderful article. http://skillshared.blogspot.in/2012/11/how-to-create-multi-module-project-with.html Thanks Semika Loku Kaluge

Unable to convert MySQL date/time value to System.DateTime - Solved

Few days back I got an exception like 'Unable to convert Mysql date/time value to system.datetime' but this happened only after deploying and locally everything was working fine. After googling for sometimes found the reason that, it was due to the formatting difference between Mysql and C# also empty date value is causing some issue. Later found the below solution to fix'em. Add an extra property(Convert Zero Datetime = true) to connectino string. e.g server=localhost;User Id=root;password=pwd;database=test; Convert Zero Datetime=true Solution obtained from StackOverflow :)

Converting String to a Executable line in JAVA

I've been searching for converting a string into a executable line so that I could process it... after searching for sometime, as usual I got a solution in the name of BeanShell scripting awesome one... This is another scripting language built with Java, which is powerful and was able to solve my need... This is the link for it : http://www.beanshell.org/manual/bshmanual.html#Download_and_Run_BeanShell Hope this helps you as well... If anyone requires any help on this, a basic one ;) ... sure post a comment, will help if I could...