32
Hibernate (Object Relational Mapping) Kishore Tripathy

Hibernate Introduction

Embed Size (px)

Citation preview

Page 1: Hibernate Introduction

Hibernate (Object Relational Mapping)

Kishore Tripathy

Page 2: Hibernate Introduction

2

AGENDA

Object/Relational Persistence and ORM Hibernate Introduction Hibernate Architecture Hibernate Configuration & Example

Page 3: Hibernate Introduction

3

Object/Relational Persistence and ORMPersistent data in modern object-oriented applications & efficient data

management

Page 4: Hibernate Introduction

4

OBJECT / RELATIONAL MAPPING

What is ORM?

Object / Relational Mapping (ORM) –

Solve the mismatch problem in middleware

An ORM solution transforms data from the object-oriented representation to the relational representation.

Elements of an ORM implementation

- a programming model for the domain objects

- an API for performing CRUD operations

- a query language or other query facility

- a metadata facility

Page 5: Hibernate Introduction

5

DOMAIN MODEL AND THE PARADIGM MISMATCH

Classes implement the business entities of our domain model attributes of the entity are properties of our Java class associations between entities are also implemented with properties

Let’s see if there is a problem mapping this to tables and columns...

UseruserName: Stringaddress: StringbillingDetails: Set

BillingDetailsaccountNumber: StringaccountName: StringaccountType: Stringuser: User

Page 6: Hibernate Introduction

6

CREATING TABLES FOR THE DOMAIN MODEL

SQL schema design for trivial cases is ... trivial:

We’ll see the problems of the O/R paradigm mismatch appear as we gradually make our model more complex…

create table USER ( USER_NAME varchar not null primary key, ADDRESS varchar not null)

create table BILLING_DETAILS ( ACCOUNT_NUMBER varchar not null primary key, ACCOUNT_NAME varchar not null, ACCOUNT_TYPE varchar not null, USER_NAME varchar foreign key references USER)

Page 7: Hibernate Introduction

7

THE PROBLEM OF GRANULARITY

should we create a new ADDRESS table? should we create a new SQL data type and change the column? user-defined data types (UDT) are not portable and the standard is weak

We usually add new columns to USER with built-in SQL data types:

UseruserName: StringbillingDetails: Set

create table USER ( USER_NAME varchar not null primary key, ADDRESS_STREET varchar not null, ADDRESS_CITY varchar not null, ADDRESS_ZIPCODE varchar not null)

Addressstreet: Stringcity: Stringzipcode: String

Page 8: Hibernate Introduction

8

THE PROBLEM OF SUBTYPES

We create subclasses of BillingDetails:

and use polymorphism in Java to implement our billing strategy.

How do we represent subtypes in our relational model?

User BillingDetails1 1..*

CreditCard Cheque

Page 9: Hibernate Introduction

9

THE PROBLEM OF ASSOCIATIONS

Object-oriented languages represent entity relationships as object references (pointers) and collections of object references

Relational databases represent entity relationships as copies of primary key values referential integrity ensured by foreign key constraints

The mismatch: object references are directional, there is no such concept in the

relational model many-to-many associations require a link table in relational databases

CREATE TABLE USER_BILLING_DETAILS (

USER_ID BIGINT FOREIGN KEY REFERENCES USER,

BILLING_DETAILS_ID BIGINT FOREIGN KEY REFERENCES BILLING_DETAILS

PRIMARY KEY (USER_ID, BILLING_DETAILS_ID)

)

Page 10: Hibernate Introduction

10

Hibernate Introduction

Page 11: Hibernate Introduction

11

WHAT IS HIBERNATE?

An Object/Relational Mapping (O/R M) API for Java Open Source (LGPL) Today a part of RedHat Principal author: Gavin King Almost a defacto standard O/R M for Java Current version 3.1 (3.2 almost final)

Page 12: Hibernate Introduction

12

HIBERNATE FEATURES Powerful and high-performance object-relational

mapping Transparent Persistence (POJO/JavaBeans) Automatic Dirty Checking Transitive Persistence Lazy Fetching Outer Join Fetching Runtime SQL Generation Three Basic Inheritance Mapping Strategies

Page 13: Hibernate Introduction

13

HIBERNATE ARCHITECTURE

Page 14: Hibernate Introduction

14

HIBERNATE ARICHITECTURE

Page 15: Hibernate Introduction

15

HIBERNATE COMMUNICATION WITH RDBMSPrerequisites : Write domain classes (as POJO classes)

Employee.java Write or generate Hibernate mapping files for the domain classes

Employee.hbm.xml Write Hibernate configuration file (perapplication)

hibernate.cfg.xml

Steps For Database: Load the Hibernate configuration file and create configuration object. It

automatically loads all hbm mapping files. Create session factory from configuration object Get one session from this session factory. Create HQL query and Execute query to perform the database operation

SessionFactory factory = new Configuration(). buildSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();

// Perform Database Operation

tx.commit();session.close();

Page 16: Hibernate Introduction

16

HELLO WORLD I The Hello World program persists Employees to database.

To demonstrate Hibernate, let’s define a persistent Employee we use a Employee persistent class, POJO style

employee

PK : emp_id (int)

emp_name : varchar

emp_salary : varchar

package com.hello;

public class Employee { private Long id; private String name; private String salary;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

} public String getName() { return name; } public void setName(String name) { this.name = name; } …}

Page 17: Hibernate Introduction

17

HELLO WORLD II

Hibernate Config File

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration

PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<property name="connection.url"> jdbc:mysql://localhost:3306/test </property>

<property name="connection.username"></property>

<property name="connection.password"></property>

<property name="show_sql">true</property>

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="myeclipse.connection.profile">mysql</property>

<mapping resource=“com/hello/Employee.hbm.xml" />

</session-factory>

</hibernate-configuration>

Page 18: Hibernate Introduction

18

HELLO WORLD III XML mapping metadata:

<?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=“hello.Employee" table=“employee">

<id name="id“ column=“emp_id">

<generator class="increment"/>

</id><property name="name"> <column name=“emp_name" /> </property>

<property name="salary"> <column name=“emp_salary" /> </property>

</class>

</hibernate-mapping>

Page 19: Hibernate Introduction

19

HELLO WORLD IV

Let's persist a Employee with Session and Transaction:

Hibernate executes this SQL:

SessionFactory factory = new Configuration(). buildSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();

Employee emp = new Employee();emp.setName(“John”);emp.setSalary(“50000”);session.save(emp);

tx.commit();session.close();

insert into employee(emp_id, emp_name,emp_sal) values (1, ‘John‘,’50000’)

Page 20: Hibernate Introduction

20

HELLO WORLD V

Let's show all persistent Employees:

SessionFactory factory = new Configuration(). buildSessionFactory();

Session session = factory.openSession();

Transaction tx = session.beginTransaction();

List employees = newSession.find("from Employee");

System.out.println(employees () + " employees (s) found:" );

for ( Iterator iter = employees.iterator(); iter.hasNext(); ) { Employee employee = (Employee) iter.next(); System.out.println(employee.getName());}

newTransaction.commit();newSession.close();

select e.emp_id, e.emp_name from employee e

Page 21: Hibernate Introduction

21

HELLO WORLD VI Let's update an Employee:

Session session = getSessionFactory().openSession();Transaction tx = session.beginTransaction();// 1 is the generated id of the first employeeEmployee emp = session.load(Employee.class, new Long(1));Employee emp = new Employee();

emp.setName(“George”);

emp.setSalary(“60000”);

session.update(emp);tx.commit();session.close();

select e.emp_id, e.emp_name from employee e where e.emp_id = 1update employee set emp_name = ‘George ‘,emp_salary=‘60000’ where emp_id=1

Page 22: Hibernate Introduction

22

AN EXAMPLE OBJECT MODEL

Page 23: Hibernate Introduction

23

THE EVENT.HBM.XML MAPPING FILE<hibernate-mapping package="com.manning.hq.ch03">

<class name="Event" table="events">

<id name="id" column="uid" type="long"

<generator class="native"/>

</id>

<property name="name" type="string" length="100"/><property name="startDate" column="start_date“ type="date"/><property name="duration" type="integer"/>

<many-to-one name="location" column="location_id“

class="Location"/><set name="speakers">

<key column="event_id"/>

<one-to-many class="Speaker"/></set><set name="attendees">

<key column="event_id"/>

<one-to-many class="Attendee"/>

</set>

</class>

</hibernate-mapping>

package com.manning.hq.ch01;

import java.util.List;

public class Event {

private String name;

private Set speakers;

private Set attendees;

private Location location;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Set getSpeakers() {

return this.speakers;

}

public void setSpeakers(Set speakers) {

this.speakers = speakers;

}

public Location getLocation() {

return location;

}

public void setLocation(Location location) {

this.location = location;

}

}

Page 24: Hibernate Introduction

24

HIBERNATE QUERY OPTIONS

Hibernate Query Language (HQL) • object-oriented dialect of ANSI SQL Criteria queries (QBC)

• extensible framework for query objects• includes Query By Example (QBC)

Native SQL queries• direct passthrough with automatic mapping• named SQL queries in metadata

Page 25: Hibernate Introduction

25

QUERY EXAMPLE

HQL Query

Simplest HQL query

Query q = session.createQuery("from Event");

List results = q.list();

Using Parameter

Query q = session.createQuery("from Event where name = ? ");

q.setParameter(0, "Opening Plenary");

q.setMaxResults(5);

List results = q.list();

Criteria criteria = session.createCriteria(Event.class);

criteria.add(Restrictions.between("duration",

new Integer(60), new Integer(90) );

criteria.add( Restrictions.like("name", "Presen%") );

criteria.addOrder( Order.asc("name") );

List results = criteria.list();

The Criteria query is essentially the same as the following HQL:

from Event e where (e.duration between 60 and 90) and (e.name like 'Presen%') order by e.name

Criteria Query

Page 26: Hibernate Introduction

26

AUTOMATIC DIRTY OBJECT CHECKING

Retrieve an Event and change the description:

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

Event event =(Event ) session.get(Event .class, eventId);

event.setName(newName);

tx.commit();

session.close();

Page 27: Hibernate Introduction

27

TRANSITIVE PERSISTENCE

Retrieve an Event and create a new Speaker:

Speaker speaker = new Speaker ()

Speaker.setName(“John”);

Session session = sessionFactory.openSession();

Transaction tx = session.beginTransaction();

Event event =(Event ) session.get(Event .class, eventId);

speaker.setEvent(event );

event.getSpeakers().add(speaker);

tx.commit();

session.close();

Page 28: Hibernate Introduction

28

CASCADESThe cascade types that you are most likely to use are the following: all—All operations are passed to child entities: save, update, and

delete. save-update—Save and update (INSERT and UPDATE, respectively)

are passed to child entities. delete—Deletion operations are passed to child entities. delete-orphan—All operations are passed to child entities, and

objects no longer associated with the parent object are deleted.

<set name="speakers" cascade="delete"> <key column="event_id"/> <one-to-many class="Speaker"/> </set>

Page 29: Hibernate Introduction

29

OPTIMIZING DATA ACCESS

Minimize row reads Use lazy fetching

Minimize database roundtrips Use outer join fetching

<many-to-one name="location" class="Location" fetch="join"/>

<many-to-one name="location" class="Location" fetch="select"/>

Page 30: Hibernate Introduction

30

INHERITANCE

Hibernate supports three different inheritance persistence strategies:

Table per class hierarchy Table per subclass Table per concrete class

<class name="Event" table="events">

<id name="event_id" type="long">

<generator class="native"/>

</id>

<joined-subclass name="ConferenceEvent" table="conf_events">

<key column="event_id"/>

...

</joined-subclass>

<joined-subclass name="NetworkingEvent" table="net_events">

<key column="event_id"/>

...

</joined-subclass>

</class>

Table-per-subclass

Table-per-subclass mapping

Page 31: Hibernate Introduction

31

Questions

Page 32: Hibernate Introduction

32

Thank you !