SlideShare una empresa de Scribd logo
1 de 26
Java & JEE Training
Session 39 – Hibernate (Part 1 of 2)
Page 1Classification: 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 2Classification: 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 3Classification: Restricted
Hibernate Architecture – High Level
Page 4Classification: Restricted
Hibernate – Detailed Architecture
Page 5Classification: 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 6Classification: Restricted
Hibernate jar files…
• Download from Hibernate official site
http://hibernate.org/orm/downloads/
Page 7Classification: Restricted
Hibernate tools download
• http://tools.jboss.org/downloads/
Page 8Classification: 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 9Classification: 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 10Classification: 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 11Classification: 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 12Classification: 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 13Classification: 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 14Classification: 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 15Classification: 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 16Classification: 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 17Classification: 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 18Classification: Restricted
Your first Hibernate project – Steps in detail
To run the hibernate application, right click on the StoreData class - Run As -
Java Application.
Page 19Classification: 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 20Classification: 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 21Classification: 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 22Classification: 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 23Classification: Restricted
DAO Design Pattern in Java
Page 24Classification: 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 25Classification: Restricted
Thank you!

Más contenido relacionado

La actualidad más candente

Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web AppsSession 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web AppsPawanMM
 
Session 35 - Design Patterns
Session 35 - Design PatternsSession 35 - Design Patterns
Session 35 - Design PatternsPawanMM
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1PawanMM
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2PawanMM
 
Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4PawanMM
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2 Hitesh-Java
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction Hitesh-Java
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCHitesh-Java
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansPawanMM
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessionsvantinhkhuc
 
Web Basics
Web BasicsWeb Basics
Web BasicsHui Xie
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & AjaxAng Chen
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: ServletsFahad Golra
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0Jeffrey West
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Hitesh-Java
 

La actualidad más candente (18)

Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web AppsSession 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
 
Session 35 - Design Patterns
Session 35 - Design PatternsSession 35 - Design Patterns
Session 35 - Design Patterns
 
Session 36 - JSP - Part 1
Session 36 - JSP - Part 1Session 36 - JSP - Part 1
Session 36 - JSP - Part 1
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4Session 28 - Servlets - Part 4
Session 28 - Servlets - Part 4
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Web Basics
Web BasicsWeb Basics
Web Basics
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & Ajax
 
Lecture 2: Servlets
Lecture 2:  ServletsLecture 2:  Servlets
Lecture 2: Servlets
 
WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0WebLogic Developer Webcast 1: JPA 2.0
WebLogic Developer Webcast 1: JPA 2.0
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
 

Similar a Session 39 - Hibernate - Part 1

Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1Hitesh-Java
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfMytrux1
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationLuis Goldster
 
Hibernate basics
Hibernate basicsHibernate basics
Hibernate basicsAathikaJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java PlatformSivakumar Thyagarajan
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tooljavaease
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 

Similar a Session 39 - Hibernate - Part 1 (20)

Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate 18052012
Hibernate 18052012Hibernate 18052012
Hibernate 18052012
 
Hibernate basics
Hibernate basicsHibernate basics
Hibernate basics
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Data access
Data accessData access
Data access
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 

Más de PawanMM

Session 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAXSession 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAXPawanMM
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCPawanMM
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPPawanMM
 
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationSession 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationPawanMM
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationPawanMM
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionPawanMM
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1PawanMM
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBCPawanMM
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, SerializationPawanMM
 
Session 21 - Inner Classes
Session 21 - Inner ClassesSession 21 - Inner Classes
Session 21 - Inner ClassesPawanMM
 
Session 20 - Collections - Maps
Session 20 - Collections - MapsSession 20 - Collections - Maps
Session 20 - Collections - MapsPawanMM
 
Session 19 - Review Session
Session 19 - Review SessionSession 19 - Review Session
Session 19 - Review SessionPawanMM
 
Session 18 - Review Session and Attending Java Interviews
Session 18 - Review Session and Attending Java InterviewsSession 18 - Review Session and Attending Java Interviews
Session 18 - Review Session and Attending Java InterviewsPawanMM
 
Session 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsSession 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsPawanMM
 
Session 16 - Collections - Sorting, Comparing Basics
Session 16 - Collections - Sorting, Comparing BasicsSession 16 - Collections - Sorting, Comparing Basics
Session 16 - Collections - Sorting, Comparing BasicsPawanMM
 

Más de PawanMM (16)

Session 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAXSession 48 - JS, JSON and AJAX
Session 48 - JS, JSON and AJAX
 
Session 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVCSession 46 - Spring - Part 4 - Spring MVC
Session 46 - Spring - Part 4 - Spring MVC
 
Session 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOPSession 45 - Spring - Part 3 - AOP
Session 45 - Spring - Part 3 - AOP
 
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based ConfigurationSession 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
 
Session 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate IntegrationSession 42 - Struts 2 Hibernate Integration
Session 42 - Struts 2 Hibernate Integration
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 Introduction
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Session 23 - JDBC
Session 23 - JDBCSession 23 - JDBC
Session 23 - JDBC
 
Session 22 - Java IO, Serialization
Session 22 - Java IO, SerializationSession 22 - Java IO, Serialization
Session 22 - Java IO, Serialization
 
Session 21 - Inner Classes
Session 21 - Inner ClassesSession 21 - Inner Classes
Session 21 - Inner Classes
 
Session 20 - Collections - Maps
Session 20 - Collections - MapsSession 20 - Collections - Maps
Session 20 - Collections - Maps
 
Session 19 - Review Session
Session 19 - Review SessionSession 19 - Review Session
Session 19 - Review Session
 
Session 18 - Review Session and Attending Java Interviews
Session 18 - Review Session and Attending Java InterviewsSession 18 - Review Session and Attending Java Interviews
Session 18 - Review Session and Attending Java Interviews
 
Session 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, SetsSession 17 - Collections - Lists, Sets
Session 17 - Collections - Lists, Sets
 
Session 16 - Collections - Sorting, Comparing Basics
Session 16 - Collections - Sorting, Comparing BasicsSession 16 - Collections - Sorting, Comparing Basics
Session 16 - Collections - Sorting, Comparing Basics
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

Session 39 - Hibernate - Part 1

  • 1. Java & JEE Training Session 39 – Hibernate (Part 1 of 2)
  • 2. Page 1Classification: 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.
  • 3. Page 2Classification: 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.
  • 4. Page 3Classification: Restricted Hibernate Architecture – High Level
  • 5. Page 4Classification: Restricted Hibernate – Detailed Architecture
  • 6. Page 5Classification: 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.
  • 7. Page 6Classification: Restricted Hibernate jar files… • Download from Hibernate official site http://hibernate.org/orm/downloads/
  • 8. Page 7Classification: Restricted Hibernate tools download • http://tools.jboss.org/downloads/
  • 9. Page 8Classification: 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
  • 10. Page 9Classification: 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.
  • 11. Page 10Classification: 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; } }
  • 12. Page 11Classification: 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
  • 13. Page 12Classification: 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>
  • 14. Page 13Classification: 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; } }
  • 15. Page 14Classification: 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();
  • 16. Page 15Classification: 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();
  • 17. Page 16Classification: 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();
  • 18. Page 17Classification: 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();
  • 19. Page 18Classification: Restricted Your first Hibernate project – Steps in detail To run the hibernate application, right click on the StoreData class - Run As - Java Application.
  • 20. Page 19Classification: 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.
  • 21. Page 20Classification: 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
  • 22. Page 21Classification: 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; } }
  • 23. Page 22Classification: 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.
  • 24. Page 23Classification: Restricted DAO Design Pattern in Java
  • 25. Page 24Classification: 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