My HB
My HB
Objectives
2
Understanding Object to relation persistence
3
Problems with JDBC
4
Understanding Object to relation persistence
Object:
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
• 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
8
Why ORM?
• Minimize LOC
9
Transparent Persistence
with ORM
10
Available ORM solutions
• TopLink (Oracle)
• Cocobase (Thought)
11
What is Hibernate ?
• Open Source
• Mature
• 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
14
Hibernate Architecture
Application
Persistence Objects
Hibernate
Database
15
“Full-Cream” Architecture
TransientObjects Application
Persistent
Objects
SessionFactory
Session Transaction
Transaction Connection
Factory Provider
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
18
First Hibernate Application
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
23
Hibernate Properties:
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
27
The Main Class (Persisting the Employee)
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
32
Session Factory
• Is thread-safe
• calling close() on SessionFactory object release all resources and closes connection
33
Session
Not thread-safe.
Maintains transactions
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.
35
Introduction to HQL
• Similar to EJBQL
• 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
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.
39
Binding parameters
40
Using named Queries
<query name=“findEmployeeByDept”>
<![CDATA[
from item item where item.description like : description }}>
</query>
41
Example of simple Query
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
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
46
Expressions
47
Ordering query results
48
Example of Query using Ordering
49
Thank You
50