SlideShare a Scribd company logo
Object Relational
Mapping (ORM)
and Hibernate
INF5750/9750 - Lecture 2 (Part III)
Problem area
● When working with object-oriented systems, there’s a
mismatch between the object model and the relational
database
● How do we map one to the other?
public class Student
{
private String name;
private String address;
private Set<Course> courses;
private Set<Degree> degrees;
}
Java object with properties
and associations
Relational database
with tables and columns
Problem area
● How to map associations between objects?
○ References are directional, foreign keys not
○ Foreign keys can’t represent many-to-many associations
Student Degree
N N
public class Student
{
private Collection<Degree> degrees;
...
DEGREE
degree_id
type
name
STUDENT
student_id
name
address
degree_id
Java
Relational
database
Need for ORM
● Write SQL conversion methods by hand using JDBC
○ Tedious and requires lots of code
○ Extremely error-prone
○ Non-standard SQL ties the application to specific databases
○ Vulnerable to changes in the object model
○ Difficult to represent associations between objects
Student Course
Degree
public void addStudent( Student student )
{
String sql = ”INSERT INTO student ( name, address ) VALUES ( ’” +
student.getName() + ”’, ’” + student.getAddress() + ”’ )”;
// Initiate a Connection, create a Statement, and execute the query
}
Approaches to ORM
● Use Java serialization – write application state to a file
○ Can only be accessed as a whole
○ Not possible to access single objects
● Object oriented database systems
○ No complete query language implementation exists
○ Lacks necessary features
The preferred solution
● Use a Object-Relational Mapping System (eg. Hibernate)
● Provides a simple API for storing and retrieving Java
objects directly to and from the database
● Non-intrusive: No need to follow specific rules or design
patterns
● Transparent: Your object model is unaware
Student Course
Degree
ORM / Hibernate
Magic happens
here!
(Domain model) (Relational database)
ORM and Architecture
Presentation Layer
Service/Business Layer
Persistence Layer
ORM / Hibernate
(Database)
Domain
Model
● Middleware that
manages persistence
● Provides an abstraction
layer between the
domain model and the
database
Example app: The EventManager
Java
objects
Hibernate
mapping files
Hibernate
configuration
Hibernate
API
Java objects (POJO)
public class Event
{
private int id;
private String title;
private Date date;
private Set<Person> persons = new HashSet<Person>();
public Event() {
}
public int getId() {
return id;
}
private void setId( int id ) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle( String title ) {
this.title = title;
}
// Getter and setter for date and persons
}
Declare accessors and mutators for
persistent fields (optional)
● Properties need not be declared
public - Hibernate can persist a
property with a default, protected or
private get / set pair.
No-argument constructor
(required)
Identifier property
(optional)
Prefer non-final classes
(optional)
Example app: The EventManager
Java
objects
Hibernate
mapping files
Hibernate
configuration
Hibernate
API
Hibernate mapping files
● Tells Hibernate which tables and columns to use to load
and store objects
DTD
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name=”no.uio.inf5750.Event” table=”events”>
<id name="id” column=”event_id”>
<generator class="native"/>
</id>
<property name=”title” not-null=”true” unique=”true”/>
<property name=”date” type=”date” column=”event_date”/>
<set name=”persons” table=”event_persons”>
<key column=”event_id”/>
<many-to-many column=”person_id”
class=”no.uio.inf5750.example.model.Person”/>
</set>
</class>
</hibernate-mapping>
Class element
Identifier mapping & generation
Property mapping
Filename: Event.hbm.xml
Unidirectional many-to-many
association mapping
Property mapping
...
<property name=”title” not-null=”true” unique=”true”/>
<property name=”date” type=”Date” column=”event_date”/>
...
The name property refers
to the get/set-methods
Property name used as
default if no column is specified
Types are Hibernate mapping types.
Hibernate will guess if no type is specified.
Title must be
not null and unique
Association mapping
...
<set name=”persons” table=”event_persons”>
<key column=”event_id”/>
<many-to-many column=”person_id”
class=”no.uio.inf5750.example.model.Person”/>
</set>
...
The name property refers
to the get/set-methods
Many-to-many associations
require a link table
Column name
for ”this” side
of association
Column name
for ”other” side
of association
Reference to the
associated class
Hibernate mapping types
● Hibernate will translate Java types to SQL / database types
for the properties of your mapped classes
Java type Hibernate type SQL type
java.lang.String string VARCHAR
java.util.Date date, time DATE, TIME
java.lang.Integer, int integer INT
java.lang.Class class varchar
java.io.Serializable serializable BLOB, BINARY
Example app: The EventManager
Java
objects
Hibernate
mapping files
Hibernate
configuration
Hibernate
API
Hibernate configuration
● Also referred to hibernate properties
● Each database has a dialect
○ hibernate.dialect = org.hibernate.dialect.H2Dialect
● Must also specify:
○ JDBC driver class
○ Connection URL
○ Username
○ Password
● More later in the lecture...
Example app: The EventManager
Java
objects
Hibernate
mapping files
Hibernate
configuration
Hibernate
API
The SessionFactory interface
● When all mappings have been parsed by the org.
hibernate.cfg.Configuration, the application must obtain
a factory to get org.hibernate.Session
● SessionFactory provides org.hibernate.Session
instances to the application
● Shared among application threads
● Most important method is getCurrentSession
OR let Spring inject it for you
SessionFactory sessionFactory = cfg.buildSessionFactory();
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
….
</bean
The Session interface
● Obtained from a SessionFactory
● Main runtime interface between a Java application and
Hibernate
● Responsible for storing and retrieving objects
● Think of it as a collection of loaded objects related to a
single unit of work
Session session = sessionFactory.getCurrentSession();
Instance states
● An object instance state is related to the persistence
context
● The persistence context = a Hibernate Session instance
● Three types of instance states:
○ Transient
■ The instance is not associated with any persistence context
○ Persistent
■ The instance is associated with a persistence context
○ Detached
■ The instance was associated with a persistence context which
has been closed – currently not associated
The Session interface
Event event = new Event( ”title”, new Date() );
Integer id = (Integer) session.save( event );
Make a transient object
persistent
Event event = (Event) session.load( Event.class, id );
Load an object – if
matching row exists
Load an object – if
unsure about matching row
Event event = (Event) session.get( Event.class, id );
Delete an object – make
it transient again
session.delete( event );
The Session interface
session.update( event );
Update an object – if its
detached
Synchronize database with
persistence context
session.flush(); // Happens auto. at transaction.commit()
session.saveOrUpdate( event );
Update or save an object – if
you’re unsure about the state
The Criteria interface
● You need a query when you don’t know the identifiers of
the objects you are looking for
● Criteria used for programmatic query creation
Criteria criteria = session.createCriteria( Event.class );
List events = criteria.list();
Retrieve all instances of Event
Criteria criteria = session.createCriteria( Event.class );
criteria.add( Restrictions.eq( ”title”, ”Rolling Stones” ) );;
criteria.add( Restrictions.gt( ”date”, new Date() ) );
criteria.setMaxResults( 10 );
List events = criteria.list();
Narrow the result set
Transactions
● Transaction: A set of database operations which must
be executed in entirety or not at all
● Should end either with a commit or a rollback
● All communication with a database has to occur inside a
transaction!
Transaction begins
Operation A: INSERT INTO...
Operation B: INSERT INTO...
Transaction commit
(SUCCESS)
(ERROR)
Transaction rollback
Hibernate in real-life apps
● Spring used for SessionFactory management
○ Spring has excellent ORM integration
○ Custom SessionFactory management is “boilerplate-code”
● Spring used for Transaction management
○ Custom tx management is error prone
○ Support for declarative tx management with annotations
○ Consistent programming model across JTA, JDBC, Hibernate
● Annotate transactional methods / class with @Transactional
● Hibernate’s own connection pooling is basic. Hibernate allows
external JDBC pooling through library called C3P0
Spring-Hibernate dependencies
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
...
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.5.1-Final</version>
</dependency>
<dependency>
<groupId>geronimo-spec</groupId>
<artifactId>geronimo-spec-jta</artifactId>
<version>1.0-M1</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.2.136</version>
</dependency>
Spring-Hibernate configuration
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>hibernate/Event.hbm.xml</value>
<value>hibernate/Person.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.h2.Driver"/>
<property name="jdbcUrl" value="jdbc:h2:mem:eventmanager;DB_CLOSE_ON_EXIT=FALSE"/>
<property name="user" value="sa"/>
<property name="password" value=""/>
</bean>
Enables
annotations
Can be
injected
like any bean
Points to
mapping files
Hibernate properties
● H2 database (fast inmemory DB)
● Automatically create tables
Connection
properties
Example: The EventManager
Java
objects
Hibernate
mapping files
Hibernate
configuration
Hibernate
API
Advantages of ORM
● Productivity
○ Eliminates lots of repetitive code – focus on business logic
○ Database schema is generated automatically
● Maintainability
○ Fewer lines of code – easier to understand
○ Easier to manage change in the object model
● Database vendor independence
○ The underlying database is abstracted away
○ Can be configured outside the application
● Performance
○ Lazy loading – associations are fetched when needed
○ Caching
Resources
● Spring documentation chapter 13
http://static.springsource.org/spring/docs/3.2.x/spring-
framework-reference/html/orm.html
● Hibernate reference documentation
●www.hibernate.org -> Documentation -> Reference

More Related Content

Similar to inf5750---lecture-2.-c---hibernate-intro.pdf

Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
Make School
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
guest11106b
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
Nguyen Cao
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
Haroon Idrees
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
patinijava
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
ecosio GmbH
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
Raji Ghawi
 
Hibernate
HibernateHibernate
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
Mytrux1
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
Thodoris Bais
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 
Hibernate
HibernateHibernate
Hibernate
Prashant Kalkar
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
Hitesh-Java
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
James Johnson
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
ThchTrngGia
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
Hitesh-Java
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
PawanMM
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
IMC Institute
 
React native
React nativeReact native
React native
Vishal Dubey
 

Similar to inf5750---lecture-2.-c---hibernate-intro.pdf (20)

Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Database Programming Techniques
Database Programming TechniquesDatabase Programming Techniques
Database Programming Techniques
 
Hibernate
HibernateHibernate
Hibernate
 
hibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdfhibernate-presentation-1196607644547952-4.pdf
hibernate-presentation-1196607644547952-4.pdf
 
NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020NoSQL Endgame DevoxxUA Conference 2020
NoSQL Endgame DevoxxUA Conference 2020
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Core2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdfCore2 Document - Java SCORE Overview.pptx.pdf
Core2 Document - Java SCORE Overview.pptx.pdf
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2Session 40 - Hibernate - Part 2
Session 40 - Hibernate - Part 2
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
React native
React nativeReact native
React native
 

Recently uploaded

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
alowpalsadig
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Peter Caitens
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
kalichargn70th171
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 

Recently uploaded (20)

Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)Photoshop Tutorial for Beginners (2024 Edition)
Photoshop Tutorial for Beginners (2024 Edition)
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom KittEnhanced Screen Flows UI/UX using SLDS with Tom Kitt
Enhanced Screen Flows UI/UX using SLDS with Tom Kitt
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
A Comprehensive Guide on Implementing Real-World Mobile Testing Strategies fo...
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 

inf5750---lecture-2.-c---hibernate-intro.pdf

  • 1. Object Relational Mapping (ORM) and Hibernate INF5750/9750 - Lecture 2 (Part III)
  • 2. Problem area ● When working with object-oriented systems, there’s a mismatch between the object model and the relational database ● How do we map one to the other? public class Student { private String name; private String address; private Set<Course> courses; private Set<Degree> degrees; } Java object with properties and associations Relational database with tables and columns
  • 3. Problem area ● How to map associations between objects? ○ References are directional, foreign keys not ○ Foreign keys can’t represent many-to-many associations Student Degree N N public class Student { private Collection<Degree> degrees; ... DEGREE degree_id type name STUDENT student_id name address degree_id Java Relational database
  • 4. Need for ORM ● Write SQL conversion methods by hand using JDBC ○ Tedious and requires lots of code ○ Extremely error-prone ○ Non-standard SQL ties the application to specific databases ○ Vulnerable to changes in the object model ○ Difficult to represent associations between objects Student Course Degree public void addStudent( Student student ) { String sql = ”INSERT INTO student ( name, address ) VALUES ( ’” + student.getName() + ”’, ’” + student.getAddress() + ”’ )”; // Initiate a Connection, create a Statement, and execute the query }
  • 5. Approaches to ORM ● Use Java serialization – write application state to a file ○ Can only be accessed as a whole ○ Not possible to access single objects ● Object oriented database systems ○ No complete query language implementation exists ○ Lacks necessary features
  • 6. The preferred solution ● Use a Object-Relational Mapping System (eg. Hibernate) ● Provides a simple API for storing and retrieving Java objects directly to and from the database ● Non-intrusive: No need to follow specific rules or design patterns ● Transparent: Your object model is unaware Student Course Degree ORM / Hibernate Magic happens here! (Domain model) (Relational database)
  • 7. ORM and Architecture Presentation Layer Service/Business Layer Persistence Layer ORM / Hibernate (Database) Domain Model ● Middleware that manages persistence ● Provides an abstraction layer between the domain model and the database
  • 8. Example app: The EventManager Java objects Hibernate mapping files Hibernate configuration Hibernate API
  • 9. Java objects (POJO) public class Event { private int id; private String title; private Date date; private Set<Person> persons = new HashSet<Person>(); public Event() { } public int getId() { return id; } private void setId( int id ) { this.id = id; } public String getTitle() { return title; } public void setTitle( String title ) { this.title = title; } // Getter and setter for date and persons } Declare accessors and mutators for persistent fields (optional) ● Properties need not be declared public - Hibernate can persist a property with a default, protected or private get / set pair. No-argument constructor (required) Identifier property (optional) Prefer non-final classes (optional)
  • 10. Example app: The EventManager Java objects Hibernate mapping files Hibernate configuration Hibernate API
  • 11. Hibernate mapping files ● Tells Hibernate which tables and columns to use to load and store objects DTD <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name=”no.uio.inf5750.Event” table=”events”> <id name="id” column=”event_id”> <generator class="native"/> </id> <property name=”title” not-null=”true” unique=”true”/> <property name=”date” type=”date” column=”event_date”/> <set name=”persons” table=”event_persons”> <key column=”event_id”/> <many-to-many column=”person_id” class=”no.uio.inf5750.example.model.Person”/> </set> </class> </hibernate-mapping> Class element Identifier mapping & generation Property mapping Filename: Event.hbm.xml Unidirectional many-to-many association mapping
  • 12. Property mapping ... <property name=”title” not-null=”true” unique=”true”/> <property name=”date” type=”Date” column=”event_date”/> ... The name property refers to the get/set-methods Property name used as default if no column is specified Types are Hibernate mapping types. Hibernate will guess if no type is specified. Title must be not null and unique
  • 13. Association mapping ... <set name=”persons” table=”event_persons”> <key column=”event_id”/> <many-to-many column=”person_id” class=”no.uio.inf5750.example.model.Person”/> </set> ... The name property refers to the get/set-methods Many-to-many associations require a link table Column name for ”this” side of association Column name for ”other” side of association Reference to the associated class
  • 14. Hibernate mapping types ● Hibernate will translate Java types to SQL / database types for the properties of your mapped classes Java type Hibernate type SQL type java.lang.String string VARCHAR java.util.Date date, time DATE, TIME java.lang.Integer, int integer INT java.lang.Class class varchar java.io.Serializable serializable BLOB, BINARY
  • 15. Example app: The EventManager Java objects Hibernate mapping files Hibernate configuration Hibernate API
  • 16. Hibernate configuration ● Also referred to hibernate properties ● Each database has a dialect ○ hibernate.dialect = org.hibernate.dialect.H2Dialect ● Must also specify: ○ JDBC driver class ○ Connection URL ○ Username ○ Password ● More later in the lecture...
  • 17. Example app: The EventManager Java objects Hibernate mapping files Hibernate configuration Hibernate API
  • 18. The SessionFactory interface ● When all mappings have been parsed by the org. hibernate.cfg.Configuration, the application must obtain a factory to get org.hibernate.Session ● SessionFactory provides org.hibernate.Session instances to the application ● Shared among application threads ● Most important method is getCurrentSession OR let Spring inject it for you SessionFactory sessionFactory = cfg.buildSessionFactory(); <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> …. </bean
  • 19. The Session interface ● Obtained from a SessionFactory ● Main runtime interface between a Java application and Hibernate ● Responsible for storing and retrieving objects ● Think of it as a collection of loaded objects related to a single unit of work Session session = sessionFactory.getCurrentSession();
  • 20. Instance states ● An object instance state is related to the persistence context ● The persistence context = a Hibernate Session instance ● Three types of instance states: ○ Transient ■ The instance is not associated with any persistence context ○ Persistent ■ The instance is associated with a persistence context ○ Detached ■ The instance was associated with a persistence context which has been closed – currently not associated
  • 21. The Session interface Event event = new Event( ”title”, new Date() ); Integer id = (Integer) session.save( event ); Make a transient object persistent Event event = (Event) session.load( Event.class, id ); Load an object – if matching row exists Load an object – if unsure about matching row Event event = (Event) session.get( Event.class, id ); Delete an object – make it transient again session.delete( event );
  • 22. The Session interface session.update( event ); Update an object – if its detached Synchronize database with persistence context session.flush(); // Happens auto. at transaction.commit() session.saveOrUpdate( event ); Update or save an object – if you’re unsure about the state
  • 23. The Criteria interface ● You need a query when you don’t know the identifiers of the objects you are looking for ● Criteria used for programmatic query creation Criteria criteria = session.createCriteria( Event.class ); List events = criteria.list(); Retrieve all instances of Event Criteria criteria = session.createCriteria( Event.class ); criteria.add( Restrictions.eq( ”title”, ”Rolling Stones” ) );; criteria.add( Restrictions.gt( ”date”, new Date() ) ); criteria.setMaxResults( 10 ); List events = criteria.list(); Narrow the result set
  • 24. Transactions ● Transaction: A set of database operations which must be executed in entirety or not at all ● Should end either with a commit or a rollback ● All communication with a database has to occur inside a transaction! Transaction begins Operation A: INSERT INTO... Operation B: INSERT INTO... Transaction commit (SUCCESS) (ERROR) Transaction rollback
  • 25. Hibernate in real-life apps ● Spring used for SessionFactory management ○ Spring has excellent ORM integration ○ Custom SessionFactory management is “boilerplate-code” ● Spring used for Transaction management ○ Custom tx management is error prone ○ Support for declarative tx management with annotations ○ Consistent programming model across JTA, JDBC, Hibernate ● Annotate transactional methods / class with @Transactional ● Hibernate’s own connection pooling is basic. Hibernate allows external JDBC pooling through library called C3P0
  • 26. Spring-Hibernate dependencies ... <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> ... <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.5.1-Final</version> </dependency> <dependency> <groupId>geronimo-spec</groupId> <artifactId>geronimo-spec-jta</artifactId> <version>1.0-M1</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.2.136</version> </dependency>
  • 27. Spring-Hibernate configuration <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> <property name="dataSource" ref="dataSource"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingResources"> <list> <value>hibernate/Event.hbm.xml</value> <value>hibernate/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop> <prop key="hibernate.hbm2ddl.auto">create-drop</prop> </props> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="org.h2.Driver"/> <property name="jdbcUrl" value="jdbc:h2:mem:eventmanager;DB_CLOSE_ON_EXIT=FALSE"/> <property name="user" value="sa"/> <property name="password" value=""/> </bean> Enables annotations Can be injected like any bean Points to mapping files Hibernate properties ● H2 database (fast inmemory DB) ● Automatically create tables Connection properties
  • 28. Example: The EventManager Java objects Hibernate mapping files Hibernate configuration Hibernate API
  • 29. Advantages of ORM ● Productivity ○ Eliminates lots of repetitive code – focus on business logic ○ Database schema is generated automatically ● Maintainability ○ Fewer lines of code – easier to understand ○ Easier to manage change in the object model ● Database vendor independence ○ The underlying database is abstracted away ○ Can be configured outside the application ● Performance ○ Lazy loading – associations are fetched when needed ○ Caching
  • 30. Resources ● Spring documentation chapter 13 http://static.springsource.org/spring/docs/3.2.x/spring- framework-reference/html/orm.html ● Hibernate reference documentation ●www.hibernate.org -> Documentation -> Reference