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

PPT
JDBC – Java Database Connectivity
Information Technology
 
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
PPT
SQLITE Android
Sourabh Sahu
 
PPT
ADO .Net
DrSonali Vyas
 
PPTX
Fragment
nationalmobileapps
 
PPT
Java collections concept
kumar gaurav
 
PPTX
JAVA AWT
shanmuga rajan
 
PPTX
Strings in Java
Abhilash Nair
 
JDBC – Java Database Connectivity
Information Technology
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
SQLITE Android
Sourabh Sahu
 
ADO .Net
DrSonali Vyas
 
Java collections concept
kumar gaurav
 
JAVA AWT
shanmuga rajan
 
Strings in Java
Abhilash Nair
 

What's hot (20)

PPT
Java Networking
Sunil OS
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPTX
REST & RESTful Web Services
Halil Burak Cetinkaya
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PPTX
Java awt (abstract window toolkit)
Elizabeth alexander
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPT
Java Servlets
BG Java EE Course
 
PPTX
Event In JavaScript
ShahDhruv21
 
PPTX
Notification android
ksheerod shri toshniwal
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPT
Angular 8
Sunil OS
 
PPTX
Servlets
Akshay Ballarpure
 
PPT
Input output streams
Parthipan Parthi
 
PPTX
collection framework in java
MANOJ KUMAR
 
PPTX
Access specifiers(modifiers) in java
HrithikShinde
 
PPTX
Networking in Java
Tushar B Kute
 
Java Networking
Sunil OS
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
REST & RESTful Web Services
Halil Burak Cetinkaya
 
PHP FUNCTIONS
Zeeshan Ahmed
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
Java awt (abstract window toolkit)
Elizabeth alexander
 
Core java complete ppt(note)
arvind pandey
 
Java Servlets
BG Java EE Course
 
Event In JavaScript
ShahDhruv21
 
Notification android
ksheerod shri toshniwal
 
Java 8 Lambda Expressions
Scott Leberknight
 
Java Streams
M Vishnuvardhan Reddy
 
Exception Handling in JAVA
SURIT DATTA
 
Angular 8
Sunil OS
 
Input output streams
Parthipan Parthi
 
collection framework in java
MANOJ KUMAR
 
Access specifiers(modifiers) in java
HrithikShinde
 
Networking in Java
Tushar B Kute
 
Ad

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
Krishnakanth Goud
 
PPT
Hibernate presentation
Manav Prasad
 
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
Krishnakanth Goud
 
Hibernate presentation
Manav Prasad
 
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
 

Recently uploaded (20)

PPTX
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
PDF
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
DOCX
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
SHREYAS PHANSE
 
agentic-ai-and-the-future-of-autonomous-systems.pdf
siddharthnetsavvies
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Top AI API Alternatives to OpenAI: A Side-by-Side Breakdown
vilush
 
This slide provides an overview Technology
mineshkharadi333
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Software Development Company | KodekX
KodekX
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
NewMind AI Monthly Chronicles - July 2025
NewMind AI
 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 

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