0% found this document useful (0 votes)
9 views50 pages

My HB

Uploaded by

Venkat Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views50 pages

My HB

Uploaded by

Venkat Sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 50

Hibernate

Objectives

1. Understanding Object to relation persistence


2. Problems with JDBC
3. Good & Bad of RDB’s
4. Impedance Mismatching
5. Goal of Object to Relational Mapping Technology
6. ORM
7. Transparent Persistence with ORM
8. ORM Solutions
9. What is Hibernate?
• Salient Features
• Components
• Architecture
10. ORM Disadvantages
11. Configuring Hibernate
12. Run thro’ First Hibernate Application
13. HQL Introduction

2
Understanding Object to relation persistence

3
Problems with JDBC

• You must manually handle database connections.


• You have to write a lot of bulky code.
• You have to manually handle associations.
• Database dependent

4
Understanding Object to relation persistence

 Object:

 Used to model business domain (Inheritance, Polymorphism, Encapsulation, and Association)

 It is the right technology to encapsulate business logic and create scalable software solutions

 We still need some way to persist and store the business objects and attributes (data )

5
Good & Bad of RDBs

Searching Joining

Sorting

Concurrency

Constraints
Difficult fine
Transaction grained model
Isolation

No Polymorphism
Stored procedures - bad

6
Impedance Mismatch

• Goal of object-oriented design is to model a process

• Goal of relational database design is normalisation

• The mapping from objects to tables can be difficult if the model contains
• complex class structures, large unstructured objects, object inheritance

• The resulting tables may store data inefficiently, or access to data may be inefficient

7
Goal of Object to Relational
Mapping Technology

• Take advantage of those things that relational database do well.

• Keep using the rich features of object technology

• Automate and reduce work (use of tools/framework)

• Ensure DBAs and Object people are both happy 

8
Why ORM?

• Natural programming model

• Minimize LOC

• Code can be run and/or tested outside the “container”

• Classes may be reused in “non-persistent” context

• Minimize database access with smart fetching strategies

• Opportunity for aggressive caching

9
Transparent Persistence
with ORM

10
Available ORM solutions

• TopLink (Oracle)

• Hibernate (Open Source)

• Cocobase (Thought)

• IBatis (Apache Foundation)

11
What is Hibernate ?

• Open Source

• Mature

• Popular (13,000 downloads/month)

• Custom API

Welcome to Hibernate 

12
Hibernate: Salient Features

Transparent
Persistence

OO Query High
Language Performance

Hibernate

Integration
Dual Layer
with
Caching
servers
Flexible
Mapping
& simple
APIs

13
Components of Hibernate

Hibernate Core

Hibernate Annotations

Hibernate Entity Manager

14
Hibernate Architecture

Application

Persistence Objects

Hibernate

Properties XML Mapping

Database

15
“Full-Cream” Architecture

TransientObjects Application
Persistent
Objects
SessionFactory
Session Transaction
Transaction Connection
Factory Provider

JNDI JDBC JTA

Database

16
Disadvantages Of ORM

• Learning curve
• Overhead
• Slower performance

17
Configuring Hibernate

 Install Hibernate
 Download Hibernate3.2.6ga from: http://www.hibernate.org/6.html
 Extract zip file at some location on your machine

 Install WTP2.0 Eclipse


 Download “wtp-all-in-one-sdk-win32” from following link:
http://download.eclipse.org/webtools/downloads/drops/R2.0/R-2.0-200706260303/
 Extract zip file at some location on your machine

 Install Hibernate Tools for Eclipse


 Download Hibernate Tools 3.2.2beta from: http://www.hibernate.org/6.html
 Extract zip file at some location on your machine

 Assumption: Oracle Client is already configured on your machine

18
First Hibernate Application

• A small standalone database application


• Requirements
• Hibernate Libraries
• Hibernate Configuration files
• A POJO class
• A hibernate mapping file
• The main class

19
The Employee Domain
Model

Employee

• id: Long
• name: String
• salary: double
• email: String

o getId()
o getName()
o getSalary()
o getEmail()
o setId()
o setName()
o setSalary()

20
The Employee POJO Class

package bo;
public class Employee {
private Long id;
private String name;
private double salary;
private String email;
public Long getId() { return id;}
public void setId(Long id) { this.id = id;}
public String getName() { return name;}
public void setName(String name) { this.name = name;}
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary;}
public String getEmail() {return email;}
public void setEmail(String email) {this.email = email;}}

21
Mapping the Employee

<hibernate-mapping package="bo">
<class name="Employee" table="Employee">
<id name="id" column="EMPID" type="long">
<generator class="sequence">
<param name="sequence">EMP_SEQUENCE</param>
</generator>
</id>
<property name="name" length="50" not-null="true"/>
<property name="email" length="50"/>
<property name="salary"/>
</class>
</hibernate-mapping>

22
Mappings

Collection type Mapping and Description


java.util.Set This is mapped with a <set> element and initialized with
java.util.HashSet
java.util.SortedSet This is mapped with a <set> element and initialized with
java.util.TreeSet. The sort attribute can be set to either a
comparator or natural ordering.
java.util.List This is mapped with a <list> element and initialized with
java.util.ArrayList
java.util.Collection This is mapped with a <bag> or <ibag> element and initialized
with java.util.ArrayList
java.util.Map This is mapped with a <map> element and initialized with
java.util.HashMap
Mapping type Description
java.util.SortedMap This is mapped with a <map> element and initialized with
Many-to-One Mapping many-to-one relationship using Hibernate
java.util.TreeMap. The sort attribute can be set to either a
One-to-One Mapping one-to-one
comparator relationship
or natural using Hibernate
ordering.
One-to-Many Mapping one-to-many relationship using Hibernate

Many-to-Many Mapping many-to-many relationship using Hibernate

23
Hibernate Properties:

S.No Properties and Description

1 hibernate.dialect
This property makes Hibernate generate the appropriate SQL for the chosen
database.
2 hibernate.connection.driver_class
The JDBC driver class.
3 hibernate.connection.url
The JDBC URL to the database instance.
4 hibernate.connection.username
The database username.
5 hibernate.connection.password
The database password.
6 hibernate.connection.pool_size
Limits the number of connections waiting in the Hibernate database connection pool.

7 hibernate.connection.autocommit
Allows autocommit mode to be used for the JDBC connection.

24
Configuring the Hibernate

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">tiger</property>
<property name="hibernate.connection.url">
jdbc:oracle:thin:@localhost:1521:lap644</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.dialect">
org.hibernate.dialect.Oracle9iDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping resource=“Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

25
SQL Dialects

Database Dialect Property


DB2 org.hibernate.dialect.DB2Dialect
HSQLDB org.hibernate.dialect.HSQLDialect
HypersonicSQL org.hibernate.dialect.HSQLDialect
Informix org.hibernate.dialect.InformixDialect
Ingres org.hibernate.dialect.IngresDialect
Interbase org.hibernate.dialect.InterbaseDialect
Microsoft SQL Server 2000 org.hibernate.dialect.SQLServerDialect
Microsoft SQL Server 2005 org.hibernate.dialect.SQLServer2005Dialect
Microsoft SQL Server 2008 org.hibernate.dialect.SQLServer2008Dialect
MySQL org.hibernate.dialect.MySQLDialect
Oracle (any version) org.hibernate.dialect.OracleDialect
Oracle 11g org.hibernate.dialect.Oracle10gDialect
Oracle 10g org.hibernate.dialect.Oracle10gDialect
Oracle 9i org.hibernate.dialect.Oracle9iDialect
PostgreSQL org.hibernate.dialect.PostgreSQLDialect
Progress org.hibernate.dialect.ProgressDialect
SAP DB org.hibernate.dialect.SAPDBDialect
Sybase org.hibernate.dialect.SybaseDialect
Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect
26
Configuration Values for
Schema

• Create - creates the schema, destroying previous data.


• Update - update the schema.
• create-drop- drop the schema at the end of the session.
• Validate - validate the schema, makes no changes to the database.

• If we are not adding the property element in configuration file hibernate.hbm2ddl.auto


the default is to make no database changes.

27
The Main Class (Persisting the Employee)

public class PersistEmployee {


public static void main(String[] args) {
try{
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Employee employee = new Employee();
employee.setName("Marry Clik");
employee.setEmail("marryc@xyz.com");
employee.setSalary(10000);
session.save(employee);
tx.commit(); session.close();
}catch(HibernateException e)
{e.printStackTrace();}}}

28
The Address Domain
Model

Address

• id: Long
• street: String
• state: string
• zip: String

o getId()
o getStreet()
o getState()
o getZip()
o setId()
o setStreet()
o setState()
osetZip()

29
The Address POJO Class

package bo;
public class Address{
private int id;
private String street;
private String city;
private String state;
private String zipcode;
public int getId() { return id; }
public void setId( int id ) { this.id = id; }
public String getStreet() { return street; }
public void setStreet( String street ) { this.street = street; }
public String getCity() { return city; }
public void setCity( String city ) { this.city = city; }
public String getState() { return state; }
public void setState( String state ) { this.state = state; }
public String getZipcode() { return zipcode; }
public void setZipcode( String zipcode ) { this.zipcode = zipcode; } }

30
Mapping the adddress

<hibernate-mapping package="bo">
<class name="Address" table="ADDRESS">
<meta attribute="class-description"> This class contains the address detail. </meta>
<id name="id" type="int" column="id">
<generator class="native"/> </id>
<property name="street" column="street_name" type="string"/>
<property name="city" column="city_name" type="string"/>
<property name="state" column="state_name" type="string"/>
<property name="zipcode" column="zipcode" type="string"/>
</class>
</hibernate-mapping>

31
Many to one Mapping

 Mapping many to one mapping


 Employee pojo class <class name="Employee" table="Employee">
<id name="id" column="EMPID" type="long">

 Private Address address; <generator class="sequence">

 public Address getAddress() { return <param


name="sequence">EMP_SEQUENCE</param
address; }
>
 public void setAddress( Address address ) {
</generator>
this.address = address; }
</id>
<property name="name" length="50" not-
null="true"/>
<property name="email" length="50"/>
<property name="salary"/>
<many-to-one name="address" column="address"
class="Address" not-null="true"/></class>

32
Session Factory

• Is used to create Hibernate Sessions

• One session factory per database

• Is thread-safe

• calling close() on SessionFactory object release all resources and closes connection

33
Session

 Is always created from SessionFactory.

 Not thread-safe.

 Works as a persistent Manager/Entity Manager

 Maintains transactions

 Maintains first level cache

 calling close() on Session object release all resources

34
SQL Dialects

• every relational database supports a different set of features and uses a slightly different
version of SQL.

• When Hibernate constructs an SQL query, it obtains appropriate syntax information for
the current database from the dialect.

• Hibernate translates the HQL queries into database- specific SQL using hints provided by
the SQL dialect classes.

• Hibernate 3 comes with over 20 different dialects.

35
Introduction to HQL

• HQL(The Hibernate Query language)

• HQL is an object-oriented dialect of the familiar relational query language SQL.

• Similar to EJBQL

• Adapted from SQL

• Used only for object retrieval not for manipulation

• Cannot be used for insert,update or delete functionality

• The HQL is not case sensitive but the object names defined in the HQL are case sensitive.

36
Why to use HQL?

• Full support fro relational operations: HQL allows representing SQl queries in the form of objects.
HQL uses classes &properties instead of tables & columns.

• Return result as object: The HQL queries return the queries result(s) in the form of objects(s), whichis
easy to use. This eliminates the need of creating the object & populate the data from result set.

• Polymorphic queries : HQL fully supports polymorphic queries. polymorphic queries results the query
results along with all the child objects if any.

• Easy to learn : Hibernate queries are easy to learn & it can be easily implemented in the applications.

• Support for Advance features : HQL contains many advance features such as pagination, fetch join
with dynamic profiling, inner / outer / full joins, cartesian products. It also suports Projection,
Aggregation (max,avg) & grouping, Ordering, Sub queries & SQL function calls.

• Database independent : Queries written in HQL are database independent (if database supports the
underlying feature)

37
The Query Interface

• To create a new Query instance, call either createQuery() or createSQLQuery()

• Using createQuery() you can execute the HQL Queries

• Using createSQLQuery() you can execute the native SQL queries

• Query interface supports pagination


• - You can use the selfirstResult() & the selMaxresults() to limit the query.

38
Listing and Iteration

• The Query interface provides with a list() to retrieve the queried objects.

• The Query and session interfaces also provide the iterate() method.

• Both use different strategies


- iterate() retrieves only ne object & tries to find rest of state of the object from cache
- Where as list() will retrieve all the object state from the database.

39
Binding parameters

• Two Types of binding that can be done


- Named Parameter Binding
- Positional Parameter Binding
• Using the Named Parameter Binding
- String queryString = “from Employee emp where emp, name
like :searchString”
- Use the setString(“searchstring”, searchString);
• Using the Positional Parameter Binding
-String queryString = “from Employee emp where emp.name like ?
- use the setString(0,searchString)

40
Using named Queries

The getNamedQuery() method obtains a Query instance for a named Query

The named Query is d efined in mapping metadat

<query name=“findEmployeeByDept”>
<![CDATA[
from item item where item.description like : description }}>
</query>

41
Example of simple Query

Example of a simple query

The query will retrieve all the instance of Employee

Query query = null


Query = session.create Query(“from Employee”);
Iterator iterator = query.list().iterator();
while (iterator.hasNext()){
Employee employee = (Employee)iterator.next()
System.out.println(employee.getName());
System.out.println(employee.getEmail());
System.out.println(employee.getId());
}

42
Using Aliases in Queries

The aliases is required since you will want to refer to the object & its properties in other parts of Query
-from Employee as emp (as is optional)
We may also assign aliases to associated entities, or even to elements of a collection of values ,
using a join from Employee emp inner join emp.department as dept
Aliases should follow the same rule
- use the same naming convention or aliases that you use for temporary
variables in java( eg employee, itemCount)

43
Using Polymorphic Queries

• HQL is a Object oriented Query Language


• HQL support Polymorphic Queries
• A Query made with a Employee would return instances of a class & all instances of its
subclasses

• - eg ManagerEmployee & CEO  Employee



• This would retrieve all the instances of manager, CEO, and Employee.

44
Restriction using HQL

• You can use the where clause for the restriction purposes when you don’t want to retrieve all
instances of a class

• You express constraints on the property values of objects & not the columns of database

• The where clause is used to express a restriction in both SQL & HQL & the behavior results in
the same

45
Example of restriction using
Where Clause

Example of a query with Restriction of records on basis of where clause


- The Query will retrieve on selected instances of Employee whose name
would start with N

Query query = null


Query = session.createQuery(“from Employee as emp where emp.name like ‘N%””);
Iterator iterator = query.list().iterator();
while (iterator.hasNext()){
Employee employee = (Employee)iterator.next()
System.out.printin(employee.getName());
System.out.printin(employee.getEmail());
System.out.printin(employee.getId());
}

46
Expressions

HQL supports the same basic operators as SQL

Mathemtical operators +,-,*,/


Binary comoarison operators =,>=,<=,<>,!=,like
Logical operations and, or, not
String concatination ||
SQL Scalar functions like upper () and lower()
Parentheses () indicate grouping
In, between, is null
JDBC IN parameters?
Named parameters :name, :start_date,:x1
SQL literals ‘foo’, 69, ‘1970-01-01 10:00:01.0’

47
Ordering query results

Result can be ordered in HQL

HQL provides an order by clause, similar to SQL


You specify ascending & descending order using asc or desc
You can also order by multiple properties

48
Example of Query using Ordering

Query query = query


session.createQuery(“from Employee as emp order by emp.name”);
Iterator iterator = query.list().iterator();
while (iterator.hasNext()){
Employee employee = (Employee)iterator.next()
System.out.printin(employee.getName());
System.out.printin(employee.getEmail());
System.out.printin(employee.getId());
}

49
Thank You

50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy