Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to develop your first Hibernate Application : Step by Step

A simple post providing step by step development of your first Hibernate Application in Java

1. Create a new Database Schema and Table in MySQL -

Since I am demonstrating this application on MySQL database server, please ensure you have MySQL database installed on your machine. At the time of installation please set username and password and remember it. Now after installation login to MySQL database using username and password from : Start -> Programs -> MySQL -> MySQL server 5.1 -> MySQL Command Line Client .

a. Create the database named customerdb


Create database customerdb;

b. Switch to the database

use customerdb;

c. Create table named customer

CREATE TABLE customer (     
customerId INT PRIMARY KEY AUTO_INCREMENT,
customerName VARCHAR(50),
customerEmail VARCHAR(60),
customerPhone INT(15));





















2. Create a new Java Project in Eclipse -
After creating database and table let's move on to create a new Java project in Eclipse. In order to create a new Java project in Eclipse select File -> New -> Java Project to create a new Java project

A window appears as : 'Create a Java Project'. Enter Project name and click finish.


3. Add JDBC Driver and Hibernate specific libraries -
a. Add the Hibernate specific jars to it. It can be downloaded from link : http://sourceforge.net/projects/hibernate/files/hibernate4/
b. Add driver jar for specific database say am using MySql database here so I am adding the jar by name as : 'mysql-connector-java-5.1.20-bin.jar'



4. Create a JavaBean (POJO) Class -

In the project created on step 2, in the src folder create a new package say 'com.hubberspot.hibernate'. Add a new Java class and name it as Customer.java. The code is given below :



package com.hubberspot.hibernate;


public class Customer {

 private Integer customerId;
 private String customerName;
 private String customerEmail;
 private String customerPhone;

 public Customer() {

 }


 public Integer getCustomerId() {
  return customerId;
 }


 public void setCustomerId(Integer customerId) {
  this.customerId = customerId;
 }


 public String getCustomerName() {
  return customerName;
 }


 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }


 public String getCustomerEmail() {
  return customerEmail;
 }


 public void setCustomerEmail(String customerEmail) {
  this.customerEmail = customerEmail;
 }


 public String getCustomerPhone() {
  return customerPhone;
 }


 public void setCustomerPhone(String customerPhone) {
  this.customerPhone = customerPhone;
 }



}




5. Create Hibernate Configuration File -

Hibernate uses a configuration file by default name as 'hibernate.cfg.xml'. It uses this file to make database connections and necessary resource mapping file entries. It also acts and helps Hibernate as a metadata for creating a fully fledged database environment.
It is been placed in the src folder of our Java project. The Hibernate Configuration file with name 'hibernate.cfg.xml'is given below :

<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/customerdb</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>

  <!-- SQL dialect -->
  <property name="dialect">
   org.hibernate.dialect.MySQL5Dialect
  </property>

  <mapping resource="Customer.hbm.xml" />

 </session-factory>
</hibernate-configuration>



It requires following properties for effective integration of Hibernate with our application -

a. connection.driver_class : It is the JDBC Connection class for the database you are intent to use.
b. connection.url : It is the JDBC URL to the database you are intent to use in your application.
c. connection.username : Username to the database which will help us to connect.
d. connection.password : Password to the database which will help us to connect.
e. dialect : Dialect property is a special property and a mandatory one. Hibernate communicates with the underlying database using dialect class specified in the property. It acts as a metadata of database for Hibernate stating few information about database as whether it allows identity column , altering relational tables , indexes and constraints etc ...
f. mapping resource : This property helps Hibernate about the Entities used in the application and it has name of hbm xml file which tells Hibernate that this entity has a separate xml, which will have information that helps Hibernate to map object state to relational tables.



6. Create Hibernate Mapping File -
Hibernate Mapping files are the configuration files to Hibernate which helps it to map objects to relational database. It helps Hibernate to persist objects to database. This file generally follows a naming convension having the name of table in database + .hbm.xml . In our case it is Customer.hbm.xml . It is been placed in the src folder of our Java project.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hubberspot.hibernate.Customer" table="customer"
  catalog="customerdb">
  <id name="customerId" type="java.lang.Integer">
   <column name="customerId"></column>
   <generator class="identity"></generator>
  </id>

  <property name="customerName" type="java.lang.String">
   <column name="customerName" length="50"></column>
  </property>

  <property name="customerEmail" type="java.lang.String">
   <column name="customerEmail" length="60"></column>
  </property>

  <property name="customerPhone" type="java.lang.Long">
   <column name="customerPhone" length="15"></column>
  </property>

 </class>
</hibernate-mapping>



7. Create a HibernateTest.java class to run the application -

package com.hubberspot.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateTest {
 public static void main(String[] args) {

  // SessionFactory gives us a factory of sessions
  // Usually SessionFactory is been configured by the 
  // configuration file named as hibernate.cfg.xml
  // buildSessionFactory() builds the sessionFactory for us
  SessionFactory sessionFactory = new Configuration().
    configure().buildSessionFactory();

  // Session is created by calling openSession()
  // method on SessionFactory object
  Session session = sessionFactory.openSession();
  // Creating a transaction from session
  Transaction tx = session.beginTransaction();

  // Creating a Customer object 
  Customer customer = new Customer();
  // setting customer name , email and phone
  customer.setCustomerName("hubberspot");
  customer.setCustomerEmail("jonty@hubberspot.com");
  customer.setCustomerPhone(89289867L);
  // Saving the Customer into the database 
  session.save(customer);
  // Commiting the transaction
  session.getTransaction().commit();
  // closing the session
  session.close();

 }
}




Table data in the database -


 
© 2021 Learn Java by Examples Template by Hubberspot