SlideShare a Scribd company logo
Java Hibernate Training
Hibernate (Part 1 of 2)
Page 1Classification: Restricted
Agenda
• Hibernate
• Advantage of hibernate
• Hibernate Architecture
• Hibernate project
• Hibernate with Annotations
• DAO Design Pattern in Java
Page 2Classification: Restricted
Hibernate
• Hibernate framework simplifies the development of java application to
interact with the database.
• Hibernate is an open source, lightweight, ORM (Object Relational
Mapping) tool.
• An ORM tool simplifies the data creation, data manipulation and data
access. It is a programming technique that maps the object to the data
stored in the relational database.
Page 3Classification: Restricted
Advantages of Hibernate
• Open-source and Lightweight: Hibernate framework is open-source and
lightweight.
• Fast performance: The performance of hibernate framework is fast because cache
is internally used in hibernate framework. There are two types of cache in hibernate
framework first level cache and second level cache. First level cache is enabled by
default.
• Database Independent query: HQL (Hibernate Query Language) is the object-
oriented version of SQL. It generates the database independent queries. So you
don't need to write database specific queries. Before Hibernate, If database is
changed for the project, we need to change the SQL query as well that leads to the
maintenance problem.
• Automatic table creation: Hibernate framework provides the facility to create the
tables of the database automatically. So there is no need to create tables in the
database manually.
• Simplifies complex join: To fetch data form multiple tables is easy in hibernate
framework.
• Provides query statistics and database status: Hibernate supports Query cache and
provide statistics about query and database status.
Page 4Classification: Restricted
Hibernate Architecture – High Level
Page 5Classification: Restricted
Hibernate – Detailed Architecture
Page 6Classification: Restricted
Hibernate Architecture – Important Elements
• SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds second
level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory
method to get the object of Session.
• Session
The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of
Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert, update and delete the object. It
also provides factory methods for Transaction, Query and Criteria.
• Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
• ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from DriverManager or
DataSource. It is optional.
• TransactionFactory
It is a factory of Transaction. It is optional.
Page 7Classification: Restricted
Hibernate jar files…
• Download from Hibernate official site
http://hibernate.org/orm/downloads/
Page 8Classification: Restricted
Hibernate tools download
• http://tools.jboss.org/downloads/
Page 9Classification: Restricted
Your first Hibernate project
• Create the java project
• Add jar files for hibernate
• Create the Persistent class
• Create the mapping file for Persistent class
• Create the Configuration file
• Create the class that retrieves or stores the persistent object
• Run the application
Page 10Classification: Restricted
Your first Hibernate project – Steps in detail
• Create the java project by File Menu - New - project - java project . Now
specify the project name e.g. firsthb then next - finish
• To add the jar files Right click on your project - Build path - Add external
archives. In this example, we are connecting the application with oracle
database. So you must add the ojdbc14.jar file as well.
Page 11Classification: Restricted
Your first Hibernate project – Steps in detail
//Create the POJO class
public class Employee {
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
Page 12Classification: Restricted
Your first Hibernate project – Steps in detail
• Mapping file for POJO - employee.hbm.xml
<?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="Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
** INSTEAD OF WRITING A SEPARATE MAPPING FILE, GIVE MAPPING INFO IN THE POJO ITSELF
Page 13Classification: Restricted
Your first Hibernate project – Steps in detail
• Create entry in configuration file: hibernate.cfg.xml
<?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="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
<mapping resource=“department.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Page 14Classification: Restricted
Your first Hibernate project – Steps – HibernateUtil
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 th){
System.err.println("Initial SessionFactory creation failed"+th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Page 15Classification: Restricted
CRUD operations: Create
//Create student entity object
Student student = new Student();
student.setStudentName(“Bill Clinton");
student.setRollNumber(01);
student.setCourse("MCA");
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
session.save(student);
System.out.println("Inserted Successfully");
session.getTransaction().commit();
session.close();
sessionFactory.close();
Page 16Classification: Restricted
CRUD operations: Read
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
Query query = session.createQuery("from Student");
List students = query.list();
for(Student student : students) {
System.out.println("Roll Number: "+student.getRollNumber()+", Student
Name: "+student.getStudentName()+", Course: "+student.getCourse());
}
sessionFactory.close();
Page 17Classification: Restricted
CRUD operations: Update
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
Student student = (Student)session.get(Student.class, 2);
student.setStudentName(“Pawan Kumar");
System.out.println("Updated Successfully");
session.getTransaction().commit();
sessionFactory.close();
Page 18Classification: Restricted
CRUD operations: Delete
//Create session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//getting session object from session factory
Session session = sessionFactory.openSession();
//getting transaction object from session object
session.beginTransaction();
Student student = (Student)session.load(Student.class, 4);
session.delete(student);
System.out.println("Deleted Successfully");
session.getTransaction().commit();
sessionFactory.close();
Page 19Classification: Restricted
Your first Hibernate project – Steps in detail
To run the hibernate application, right click on the StoreData class - Run As -
Java Application.
Page 20Classification: Restricted
Hibernate with Annotations
• The hibernate application can be created with annotation. There are many
annotations that can be used to create hibernate application such as
@Entity, @Id, @Table etc.
• Hibernate Annotations are based on the JPA 2 specification and supports all
the features.
• All the JPA annotations are defined in the javax.persistence.* package.
Hibernate EntityManager implements the interfaces and life cycle defined
by the JPA specification.
• The core advantage of using hibernate annotation is that you don't need
to create mapping (hbm) file. Here, hibernate annotations are used to
provide the meta data.
Page 21Classification: Restricted
Hibernate with Annotations
• Add the jar file for oracle (if your database is oracle) and annotation
o hibernate-commons-annotations.jar
o ejb3-persistence.jar
o hibernate-annotations.jar
• Create the Persistent class
• Annotations used:
o @Entity annotation marks this class as an entity.
o @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 by default.
o @Id annotation marks the identifier for this entity.
o @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 by default.
• Add mapping of Persistent class in configuration file
• Create the class that retrieves or stores the persistent object
Page 22Classification: Restricted
Hibernate with Annotations
@Entity
@Table(name= "emp500")
public class Employee {
@Id
private int id;
private String firstName,lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
Page 23Classification: Restricted
Exercise of Web application using Hibernate…
• 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 access code.
• As we create the simple application in hibernate, we don't need to perform
any extra operations in hibernate for creating web application. In such case,
we are getting the value from the user using the JSP file.
Page 24Classification: Restricted
DAO Design Pattern in Java
Page 25Classification: Restricted
Topics to be covered in next session
• Generator Class in Hibernate
• SQL Dialects
• Collection Mapping
• One-to-one Mapping
• Cascade Types
• Many to one / One to many
• Hibernate Lazy Loading
• Transaction Management
• HQL – Hibernate Query Language
• HCQL – Hibernate Criteria Query Language
• Hibernate Caching
Page 26Classification: Restricted
Thank you!

More Related Content

What's hot (20)

PPT
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
PPTX
Constructor in java
Madishetty Prathibha
 
PPTX
MULTI THREADING IN JAVA
VINOTH R
 
PPTX
Java - Collections framework
Riccardo Cardin
 
PPTX
Classes, objects in JAVA
Abhilash Nair
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PPTX
Control statements in java
Madishetty Prathibha
 
PPTX
Java program structure
shalinikarunakaran1
 
PPTX
Arrays in Java
Abhilash Nair
 
PPTX
Constructor ppt
Vinod Kumar
 
PDF
Object Oriented Programming Lab Manual
Abdul Hannan
 
PPTX
Ajax
Tech_MX
 
PDF
Arrays in Java
Naz Abdalla
 
PPTX
Arrays in Data Structure and Algorithm
KristinaBorooah
 
PDF
Java threads
Prabhakaran V M
 
PPTX
Inheritance in java
RahulAnanda1
 
PPS
Interface
kamal kotecha
 
PPT
RECURSION IN C
v_jk
 
PPTX
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
PPTX
Java(Polymorphism)
harsh kothari
 
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Constructor in java
Madishetty Prathibha
 
MULTI THREADING IN JAVA
VINOTH R
 
Java - Collections framework
Riccardo Cardin
 
Classes, objects in JAVA
Abhilash Nair
 
Java 8 Lambda Expressions
Scott Leberknight
 
Control statements in java
Madishetty Prathibha
 
Java program structure
shalinikarunakaran1
 
Arrays in Java
Abhilash Nair
 
Constructor ppt
Vinod Kumar
 
Object Oriented Programming Lab Manual
Abdul Hannan
 
Ajax
Tech_MX
 
Arrays in Java
Naz Abdalla
 
Arrays in Data Structure and Algorithm
KristinaBorooah
 
Java threads
Prabhakaran V M
 
Inheritance in java
RahulAnanda1
 
Interface
kamal kotecha
 
RECURSION IN C
v_jk
 
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Java(Polymorphism)
harsh kothari
 

Similar to Hibernate - Part 1 (20)

PPSX
Hibernate - Part 2
Hitesh-Java
 
PPTX
Session 40 - Hibernate - Part 2
PawanMM
 
PPTX
Session 39 - Hibernate - Part 1
PawanMM
 
PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
PPT
Hibernate basics
AathikaJava
 
PPT
Java Hibernate Basics
DeeptiJava
 
PDF
Hibernate Presentation
guest11106b
 
PPT
Hibernate
vaishnavmem
 
PDF
hibernate-presentation-1196607644547952-4.pdf
Mytrux1
 
PDF
Hibernate presentation
Luis Goldster
 
PPTX
Hibernate
Mallikarjuna G D
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
ODP
Hibernate complete Training
sourabh aggarwal
 
PDF
Apache Cayenne for WO Devs
WO Community
 
PPT
Hibernate presentation
Manav Prasad
 
PPT
Hibernate presentation
Krishnakanth Goud
 
ODP
Hibernate 18052012
Manisha Balwadkar
 
PPTX
Session 24 - JDBC, Intro to Enterprise Java
PawanMM
 
PDF
Data access
Joshua Yoon
 
PPTX
The Best Way to Become an Android Developer Expert with Android Jetpack
Ahmad Arif Faizin
 
Hibernate - Part 2
Hitesh-Java
 
Session 40 - Hibernate - Part 2
PawanMM
 
Session 39 - Hibernate - Part 1
PawanMM
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate basics
AathikaJava
 
Java Hibernate Basics
DeeptiJava
 
Hibernate Presentation
guest11106b
 
Hibernate
vaishnavmem
 
hibernate-presentation-1196607644547952-4.pdf
Mytrux1
 
Hibernate presentation
Luis Goldster
 
Hibernate
Mallikarjuna G D
 
Hibernate tutorial
Mumbai Academisc
 
Hibernate complete Training
sourabh aggarwal
 
Apache Cayenne for WO Devs
WO Community
 
Hibernate presentation
Manav Prasad
 
Hibernate presentation
Krishnakanth Goud
 
Hibernate 18052012
Manisha Balwadkar
 
Session 24 - JDBC, Intro to Enterprise Java
PawanMM
 
Data access
Joshua Yoon
 
The Best Way to Become an Android Developer Expert with Android Jetpack
Ahmad Arif Faizin
 
Ad

More from Hitesh-Java (20)

PPSX
Spring - Part 4 - Spring MVC
Hitesh-Java
 
PPSX
Spring - Part 3 - AOP
Hitesh-Java
 
PPSX
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PPSX
JSP - Part 2 (Final)
Hitesh-Java
 
PPSX
JSP - Part 1
Hitesh-Java
 
PPSX
Struts 2 - Hibernate Integration
Hitesh-Java
 
PPSX
Struts 2 - Introduction
Hitesh-Java
 
PPSX
JDBC Part - 2
Hitesh-Java
 
PPSX
JDBC
Hitesh-Java
 
PPSX
Java IO, Serialization
Hitesh-Java
 
PPSX
Inner Classes
Hitesh-Java
 
PPSX
Collections - Maps
Hitesh-Java
 
PPSX
Review Session - Part -2
Hitesh-Java
 
PPSX
Review Session and Attending Java Interviews
Hitesh-Java
 
PPSX
Collections - Lists, Sets
Hitesh-Java
 
PPSX
Collections - Sorting, Comparing Basics
Hitesh-Java
 
PPSX
Collections - Array List
Hitesh-Java
 
PPSX
Object Class
Hitesh-Java
 
PPSX
Exception Handling - Continued
Hitesh-Java
 
Spring - Part 4 - Spring MVC
Hitesh-Java
 
Spring - Part 3 - AOP
Hitesh-Java
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
JSP - Part 2 (Final)
Hitesh-Java
 
JSP - Part 1
Hitesh-Java
 
Struts 2 - Hibernate Integration
Hitesh-Java
 
Struts 2 - Introduction
Hitesh-Java
 
JDBC Part - 2
Hitesh-Java
 
Java IO, Serialization
Hitesh-Java
 
Inner Classes
Hitesh-Java
 
Collections - Maps
Hitesh-Java
 
Review Session - Part -2
Hitesh-Java
 
Review Session and Attending Java Interviews
Hitesh-Java
 
Collections - Lists, Sets
Hitesh-Java
 
Collections - Sorting, Comparing Basics
Hitesh-Java
 
Collections - Array List
Hitesh-Java
 
Object Class
Hitesh-Java
 
Exception Handling - Continued
Hitesh-Java
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 

Hibernate - Part 1

  • 2. Page 1Classification: Restricted Agenda • Hibernate • Advantage of hibernate • Hibernate Architecture • Hibernate project • Hibernate with Annotations • DAO Design Pattern in Java
  • 3. Page 2Classification: Restricted Hibernate • Hibernate framework simplifies the development of java application to interact with the database. • Hibernate is an open source, lightweight, ORM (Object Relational Mapping) tool. • An ORM tool simplifies the data creation, data manipulation and data access. It is a programming technique that maps the object to the data stored in the relational database.
  • 4. Page 3Classification: Restricted Advantages of Hibernate • Open-source and Lightweight: Hibernate framework is open-source and lightweight. • Fast performance: The performance of hibernate framework is fast because cache is internally used in hibernate framework. There are two types of cache in hibernate framework first level cache and second level cache. First level cache is enabled by default. • Database Independent query: HQL (Hibernate Query Language) is the object- oriented version of SQL. It generates the database independent queries. So you don't need to write database specific queries. Before Hibernate, If database is changed for the project, we need to change the SQL query as well that leads to the maintenance problem. • Automatic table creation: Hibernate framework provides the facility to create the tables of the database automatically. So there is no need to create tables in the database manually. • Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework. • Provides query statistics and database status: Hibernate supports Query cache and provide statistics about query and database status.
  • 5. Page 4Classification: Restricted Hibernate Architecture – High Level
  • 6. Page 5Classification: Restricted Hibernate – Detailed Architecture
  • 7. Page 6Classification: Restricted Hibernate Architecture – Important Elements • SessionFactory The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session. • Session The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria. • Transaction The transaction object specifies the atomic unit of work. It is optional. The org.hibernate.Transaction interface provides methods for transaction management. • ConnectionProvider It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional. • TransactionFactory It is a factory of Transaction. It is optional.
  • 8. Page 7Classification: Restricted Hibernate jar files… • Download from Hibernate official site http://hibernate.org/orm/downloads/
  • 9. Page 8Classification: Restricted Hibernate tools download • http://tools.jboss.org/downloads/
  • 10. Page 9Classification: Restricted Your first Hibernate project • Create the java project • Add jar files for hibernate • Create the Persistent class • Create the mapping file for Persistent class • Create the Configuration file • Create the class that retrieves or stores the persistent object • Run the application
  • 11. Page 10Classification: Restricted Your first Hibernate project – Steps in detail • Create the java project by File Menu - New - project - java project . Now specify the project name e.g. firsthb then next - finish • To add the jar files Right click on your project - Build path - Add external archives. In this example, we are connecting the application with oracle database. So you must add the ojdbc14.jar file as well.
  • 12. Page 11Classification: Restricted Your first Hibernate project – Steps in detail //Create the POJO class public class Employee { private int id; private String firstName,lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } }
  • 13. Page 12Classification: Restricted Your first Hibernate project – Steps in detail • Mapping file for POJO - employee.hbm.xml <?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="Employee" table="emp1000"> <id name="id"> <generator class="assigned"></generator> </id> <property name="firstName"></property> <property name="lastName"></property> </class> </hibernate-mapping> ** INSTEAD OF WRITING A SEPARATE MAPPING FILE, GIVE MAPPING INFO IN THE POJO ITSELF
  • 14. Page 13Classification: Restricted Your first Hibernate project – Steps in detail • Create entry in configuration file: hibernate.cfg.xml <?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="dialect">org.hibernate.dialect.Oracle9Dialect</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> <property name="connection.username">system</property> <property name="connection.password">oracle</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="employee.hbm.xml"/> <mapping resource=“department.hbm.xml"/> </session-factory> </hibernate-configuration>
  • 15. Page 14Classification: Restricted Your first Hibernate project – Steps – HibernateUtil 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 th){ System.err.println("Initial SessionFactory creation failed"+th); throw new ExceptionInInitializerError(th); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } }
  • 16. Page 15Classification: Restricted CRUD operations: Create //Create student entity object Student student = new Student(); student.setStudentName(“Bill Clinton"); student.setRollNumber(01); student.setCourse("MCA"); //Create session factory object SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //getting session object from session factory Session session = sessionFactory.openSession(); //getting transaction object from session object session.beginTransaction(); session.save(student); System.out.println("Inserted Successfully"); session.getTransaction().commit(); session.close(); sessionFactory.close();
  • 17. Page 16Classification: Restricted CRUD operations: Read //Create session factory object SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //getting session object from session factory Session session = sessionFactory.openSession(); //getting transaction object from session object Query query = session.createQuery("from Student"); List students = query.list(); for(Student student : students) { System.out.println("Roll Number: "+student.getRollNumber()+", Student Name: "+student.getStudentName()+", Course: "+student.getCourse()); } sessionFactory.close();
  • 18. Page 17Classification: Restricted CRUD operations: Update //Create session factory object SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //getting session object from session factory Session session = sessionFactory.openSession(); //getting transaction object from session object session.beginTransaction(); Student student = (Student)session.get(Student.class, 2); student.setStudentName(“Pawan Kumar"); System.out.println("Updated Successfully"); session.getTransaction().commit(); sessionFactory.close();
  • 19. Page 18Classification: Restricted CRUD operations: Delete //Create session factory object SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); //getting session object from session factory Session session = sessionFactory.openSession(); //getting transaction object from session object session.beginTransaction(); Student student = (Student)session.load(Student.class, 4); session.delete(student); System.out.println("Deleted Successfully"); session.getTransaction().commit(); sessionFactory.close();
  • 20. Page 19Classification: Restricted Your first Hibernate project – Steps in detail To run the hibernate application, right click on the StoreData class - Run As - Java Application.
  • 21. Page 20Classification: Restricted Hibernate with Annotations • The hibernate application can be created with annotation. There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc. • Hibernate Annotations are based on the JPA 2 specification and supports all the features. • All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements the interfaces and life cycle defined by the JPA specification. • The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file. Here, hibernate annotations are used to provide the meta data.
  • 22. Page 21Classification: Restricted Hibernate with Annotations • Add the jar file for oracle (if your database is oracle) and annotation o hibernate-commons-annotations.jar o ejb3-persistence.jar o hibernate-annotations.jar • Create the Persistent class • Annotations used: o @Entity annotation marks this class as an entity. o @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 by default. o @Id annotation marks the identifier for this entity. o @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 by default. • Add mapping of Persistent class in configuration file • Create the class that retrieves or stores the persistent object
  • 23. Page 22Classification: Restricted Hibernate with Annotations @Entity @Table(name= "emp500") public class Employee { @Id private int id; private String firstName,lastName; public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } }
  • 24. Page 23Classification: Restricted Exercise of Web application using Hibernate… • 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 access code. • As we create the simple application in hibernate, we don't need to perform any extra operations in hibernate for creating web application. In such case, we are getting the value from the user using the JSP file.
  • 25. Page 24Classification: Restricted DAO Design Pattern in Java
  • 26. Page 25Classification: Restricted Topics to be covered in next session • Generator Class in Hibernate • SQL Dialects • Collection Mapping • One-to-one Mapping • Cascade Types • Many to one / One to many • Hibernate Lazy Loading • Transaction Management • HQL – Hibernate Query Language • HCQL – Hibernate Criteria Query Language • Hibernate Caching