0% found this document useful (0 votes)
59 views15 pages

Module 1 - Introduction To Hibernate

Uploaded by

shaik abdulla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
59 views15 pages

Module 1 - Introduction To Hibernate

Uploaded by

shaik abdulla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

Hibernate5.

4
Study Guide

Author
Som Prakash

www.jtcindia.org 1 Hibernate5.4 Study


Guide
 Hibernate is a persistence framework which is used to implement persistence
operations to interact with the database.
 Hibernate framework was provided by RedHat.
 Architect of Hibernate is Gavin King.
 Hibernate is ORM (Object Relational Mapping) tool and is best among all other
persistence frameworks like IBatis, TopLink, JDO etc.
 Hibernate can be implemented either with XML approach (Hibernate Core) or
Annotation approach (Hibernate Annotations).
 JDBC Specification is given by SUN and is implemented by various Database
Vendors.

Implementation
Java
Program
JDBC
JDBC

Uses API DB
JDBC API

 Hibernate is implemented on the top of JDBC Technology i.e. you can use Hibernate
API which internally uses JDBC to contact Database.

Java
Implementation

Hibernate
Program Runtime
System JDBC
JDBC

Uses
Uses API DB
Hibernate
JDBC API
API

www.jtcindia.org 2 Hibernate5.4 Study


Guide
 When you write the JDBC code for implementing database operations, you need to
perform the following:
try{
1. Load the Driver Class
2. Get the connection
3. Prepare the SQL Statement (***)
4. Create the JDBC Statement
5. Submit the SQL Statement to DB.
6. Process the Results (***)
}catch(Exception e){ }
finally{
7. Clean the Resources
}
challeenges of jdbc

 In the above code, more statements (1, 2, 4, 5, 7) are common across multiple JDBC
programs. This gives you the code duplication problem.
 When you write JDBC Code , you as Java Developer are responsible for:
o Getting Connection
o Writing SQL Statements.
o Creating the JDBC Statements.
o Generating Primary Keys.
o Submitting SQL Statements to DB.
o Process the Results.
o Clean the resources.
etc
 Hibernate as Persistence Framework automates these tasks and simplifies you life.

See how it is now

www.jtcindia.org 3 Hibernate5.4 Study


Guide
1) Hibernate system is responsible for taking the connections, creating statements and
releasing the resources.
Ex:
a) Customer cust=new
Customer("som","som@jtc",1234)
session.save(cust);

b) Customer cust=session.load(Customer.class,99)

2) Hibernate system is responsible for generating SQL queries which are well-tuned in
terms of performance.
3) Hibernate system is responsible for generating the values required for Primary key
columns.
unique id automcatically
4) Hibernate provides many built-In Primary key generation algorithms and also supports
to implement Custom Primary key generation algorithms.
5) Hibernate supports various mapping styles:
1) Simple Mapping
2) Collection Mapping
3) Inheritance Mapping
a. Table per sub class mapping
b. Table per class mapping
c. Table per concrete class mapping
4) Association Mapping
a. One - to - One Mapping
b. One - to - Many Mapping
c. Many- to - Many Mapping
5) Other mappings.
6) Hibernate provides various Query Languages: //not dependet on complete sql it provide other lang
a. HQL(*)
b. QBC(*)
c. Native SQL
d. Named SQL
7) Hibernate supports two ways to manage connections
a. DriverManager connections
b. DataSource connections

www.jtcindia.org 4 Hibernate5.4 Study


Guide
8) Hibernate supports two ways to manage Transactions
a. JDBC Transactions
b. JTA Transactions
9) Hibernate has in-built support for Batch Updates.
10) Hibernate provides various caching mechanism.
11) Hibernate System uses many persistent best practices and forces the developer to use
them for better performance.

A) Setup the Database


1) Create database myjtcdb;
2) use myjtcdb;
3) Create the table called mycustomers

drop table mycustomers;


create table
mycustomers( cid int
primary key,
cname char(10),
myemail char(10),
myphone int,
mycity char(10)
);

4) See the Records


select * from mycustomers;

B) SetUp the Project


5) Create the Java Project with the name Lab1
6) Add the 26 Hibernate Jars to Project Build.
7) Add Mysql Jar to Project Build.
8) Create the Package called com.jtcindia.hiberate
9) Write the Hibernate Configuration Document (src/hibernate.cfg.xml)

www.jtcindia.org 5 Hibernate5.4 Study


Guide
C) Write Entity Class with Mapping Details
10) Write the Customer Entity class under com.jtcindia.hibernate
 Private Variables
 constructors
 public setters and getters
 toString()

11) Write Mapping Annotations to Map the Customer Entity Class with mycustomers Table

D) Write Clicent Code for doing Persistenace Operations.


12) Write Lab1A for Inserting Record

Customer cust = new Customer("sp","sp@jtc",2222,"Noida");


session.save(cust);

13) Write Lab1B for Loading Record

Customer cust = session.load(Customer.class,102);

14) Write Lab1C for Updating Record

Customer cust = session.load(Customer.class,102);


cust.setEmail("som@jtc");
cust.setPhone(54321);
//session.update(cust);

15) Write Lab1A for Deleting Record

Customer cust = session.load(Customer.class,103);


session.delete(cust);

www.jtcindia.org 6 Hibernate5.4 Study


Guide
Lab1: Files Required:
1. Lab1A.java 2. Lab1B.java
3. Lab1C.java 4. Lab1D.java
5. Customer.java 6. XHibernateUtil.java
7. Hibernate.cfg.xml

1) Lab1A.java
package com.jtcindia.hibernate;

import org.hibernate.*;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class Lab1A {
public static void main(String[] args) {

Transaction tx=null;
try {
//Step 1: get the SessionFactory Object.
SessionFactorysessionFactory= XHibernateUtil.getSessionFactory();

//Step 2: Open the Session


Session session = sessionFactory.openSession();

//Step 3: Begin Transaction


tx = session.beginTransaction();

//Step4: Do Your Ops


Customer cust = new Customer("sp","sp@jtc",2222,"Noida");
session.save(cust);

//Step 5: End Tx
tx.commit();

//Step 6: Close Session


session.close();
}
catch(Exception ex) {
//Step 5: End Tx
tx.rollback();
ex.printStackTrace();
} } }

www.jtcindia.org 7 Hibernate5.4 Study


Guide
2)Lab1B.java
package com.jtcindia.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class Lab1B {
public static void main(String[] args) {

Transaction tx=null;
try {
SessionFactorysessionFactory= XHibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
tx = session.beginTransaction();

//Your Persistence Operations Here


Customer cust = session.load(Customer.class,103);
System.out.println(cust);

tx.commit();
session.close();
}
catch(Exception ex)
{ tx.rollback();
ex.printStackTrace();
}
}
}

3)Lab1C.java
package com.jtcindia.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class Lab1C {
public static void main(String[] args) {

www.jtcindia.org 8 Hibernate5.4 Study


Guide
Transaction tx=null;
try {
SessionFactorysessionFactory= XHibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
tx = session.beginTransaction();

//Your Persistence Operations Here


Customer cust = session.load(Customer.class,102);
System.out.println(cust);
cust.setEmail("som@jtc");
cust.setPhone(54321);
cust.setCity("Delhi");
//session.update(cust);

tx.commit();
session.close();
}
catch(Exception ex)
{ tx.rollback();
ex.printStackTrace();
}
}
}

4)Lab1D.java
package com.jtcindia.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class Lab1D {
public static void main(String[] args) {

Transaction tx=null;
try {
SessionFactorysessionFactory= XHibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
tx = session.beginTransaction();

//Your Persistence Operations Here


Customer cust = session.load(Customer.class,103);
System.out.println(cust);
session.delete(cust);

www.jtcindia.org 9 Hibernate5.4 Study


Guide
tx.commit();
session.close();
}
catch(Exception ex)
{ tx.rollback();
ex.printStackTrace();
}
}
}

5)Customer.java
package com.jtcindia.hibernate;

import javax.persistence.*;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
@Entity
@Table(name="mycustomers")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="cid")
private int cid;

@Column(name="cname")
private String cname;

@Column(name="myemail")
private String email;

@Column(name="myphone")
private int phone;

@Column(name="mycity")
private String city;

public Customer() {}
public Customer(String cname, String email, int phone, String city)
{ this.cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}

www.jtcindia.org 10 Hibernate5.4 Study


Guide
public Customer(in t cid, String cname, String email, int phone, String city)
{ this.cid = cid;
this.cname = cname;
this.email = email;
this.phone = phone;
this.city = city;
}
//Setters and Getters

@Override
public String toString() {
return " [" + cid + ", " + cname + ", " + email + ", " + phone + ", " + city + "]";
}
}

6)XHibernateUtil.java
package com.jtcindia.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class XHibernateUtil {

static SessionFactory sessionFactory;


static
{ try {
StandardServiceRegistryBuilder ssrbuilder=new StandardServiceRegistryBuilder();
ServiceRegistry serviceReg=ssrbuilder.configure().build();
Metadata metadata=new MetadataSources(serviceReg).getMetadataBuilder().build();
sessionFactory=metadata.getSessionFactoryBuilder().build();
}catch(Exception ex)
{ ex.printStackTrace();
}
}
public static SessionFactory getSessionFactory()
{ return sessionFactory;
}
}

www.jtcindia.org 11 Hibernate5.4 Study


Guide
7)hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD//EN" "http://hibernate.org/dtd/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/myjtcdb</property>
<property name="connection.username">root</property>
<property name="connection.password">somprakash</property>

<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>

<property name="current_session_context_class">thread</property>
<property name="hbm2ddl.auto">update</property>

<mapping class="com.jtcindia.hibernate.Customer"/>

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

Lab 2: Example using Java Based Hibernate Config.


1) Copy the Lab1 as Lab2
2) Remove hibernate.cfg.xml from src folder.
3) Rename XHibernateUtil.java as HibernateUtil.java
4) Update HibernateUtil.java
5) Run the Clients One by One

Lab1: Files Required:


1. Lab1A.java Same as Lab1
2. Lab1B.java Same as Lab1
3. Lab1C.java Same as Lab1
4. Lab1D.java Same as Lab1
5. Customer.java Same as Lab1
6. HibernateUtil.java Updated in Lab2

www.jtcindia.org 12 Hibernate5.4 Study


Guide
6) HibernateUtil.java
package com.jtcindia.hibernate;

import java.util.Properties;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
/*
* @Author : Som Prakash Rai
* @Company: JtcIndia
* */
public class HibernateUtil {
static SessionFactory sessionFactory = null;
static {
try {
Configuration cfg = new Configuration();
Properties myprops = new Properties();
myprops.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
myprops.put(Environment.URL, "jdbc:mysql://localhost:3306/myjtcdb");
myprops.put(Environment.USER, "root");
myprops.put(Environment.PASS, "somprakash");
myprops.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
myprops.put(Environment.SHOW_SQL, "true");
myprops.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
myprops.put(Environment.HBM2DDL_AUTO, "update");

cfg.setProperties(myprops);

cfg.addAnnotatedClass(Customer.class);

StandardServiceRegistryBuilder ssrbuilder = new StandardServiceRegistryBuilder();


ServiceRegistry serviceRegistry = ssrbuilder.applySettings(cfg.getProperties()).build();

sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (Exception e)
{ e.printStackTrace();
}
}

public static SessionFactory getSessionFactory()


{ return sessionFactory;
}
}

www.jtcindia.org 13 Hibernate5.4 Study


Guide
Interview Questions:
Q1) What are the Hibernate Features?
Ans:

Q2) What is the Annotation to mark POJO class as Entity Class?


Ans:

Q3) What is the Annotation for mapping the Entity Class with the Table?
Ans:

Q4) What is the Annotation for mapping the Entity Class field with with column of Table?
Ans:

Q5) What is the Annotation for mapping the Simple Primary Key?
Ans:

Q6) What happens when I specify the Primary Key Strategy as AUTO?
Ans:

Q7) What happens when I specify the Primary Key Strategy as IDENTITY?
Ans:

Q8) What is the difference between Primary Key Strategies – AUTO and IDENTITY?
Ans:

Q9) How many Session Factory Objects will be required for Hibernate Application?
Ans:

Q10) How to create Session Factory Object?


Ans:

www.jtcindia.org 14 Hibernate5.4 Study


Guide
Q11) Is it Mandatory to Manage the Transaction in JDBC?
Ans:

Q12) Is it Mandatory to Manage the Transaction in Hibernate?


Ans:

Q13) What is the default AutoCommit value in JDBC?


Ans:

Q14) What is the default AutoCommit value in Hibernate?


Ans:

Q15) How to Insert the Records into Database Table in Hibernate?


Ans:

Q16) How to Fetch the Records from Database Table in Hibernate?


Ans:

Q17) How to Update the Records of Database Table in Hibernate?


Ans:

Q18) How to Delete the Records from Database Table in Hibernate?


Ans:

www.jtcindia.org 15 Hibernate5.4 Study


Guide

You might also like