You are on page 1of 67

Welcome To The

H World of
I
B Hibernation - 3.0
E
R
N
A
T
E Praveen Soni
Development Center
A-Wing,Level 6,Tower X, Cybercity
Magarpatta City
Hadapsar
Pune-411028 (M.H), India
Tel : 91-20-66088000-01

[1]
Agenda
Problem in programming Relational DBs
Problem with EJB
H
I Hibernate Solution
B
E
What is Hibernate
R Features of Hibernate
N
A Hibernate Architecture
T
E Persistence Life Cycle
Core interfaces in hibernate

[2]
Agenda
What is ORM
Features of ORM
H
I
Configuration of Hibernate.cfg.xml
B Writing POJO Class
E
R Basic O/R Mapping
N
A Inheritance Mapping
T
E
Component Mapping
Association Mapping
Collections Mapping
[3]
Problem Programming to Relational DBs
What do relational DBs do well?

Work with large amounts of data


Searching, sorting
H
I Work with sets of data
B Joining, aggregating
E
R Sharing
N Concurrency (Transactions)
A Many applications
T
E Integrity
Constraints
Transaction isolation

[4]
Problem Programming to Relational DBs
What do relational DBs do badly?
Modeling
No polymorphism / inheritance
H No support for automatic conversion to objects
I
B Business logic
E Theres stored procedures, but:
R Very database specific
N Very coupled with the data, really belongs in the application
domain
A
T
Transaction
E
No concept of application level transactions

[5]
Problem with EJB
EJB the answer?

EJB spec tried to bridge the gap between programming


and interacting with relational dbs
H
I
EJB provides:
B
Basic persistence (CMP)
E
R Method-level transaction management
N
A Automatic management of associations
T
E EJBQL provides a very basic object query language

[6]
Problems with EJB
Noisy Programming model
Inheritance from javax.ejb
Interface / Implementation required but do we really need interfaces of our entity beans
Complex deployment descriptors
H Weird combo of checked / unchecked exceptions
I
No Polymorphism
B
E Cant Test Outside Container
R For example, in JUnit
N Why not?
A Home is an interface
T Relationships/instantiation done by container
E EJBQL too limited none of:
Aggregation/projection for reporting
Outer-join fetching
Pagination
Dynamic queries

[7]
The Hibernate Solution

Hibernate is a persistence framework aimed at solving the shortcomings


presented by EJB2.

H Persistence classes (entities) are POJOs


I Easy to write and refactor
B Can be serialized
Can execute outside of the container (JUnit)
E
Eg.
R
public class Book {
N private Author author;
A
T public Author getAuthor()
E public void setAuthor(.
}

[8]
The Hibernate Solution (cont.)
POJO programming model
Persistent properties are not abstract
Can instantiate POJOS using new()
H Detached from persistence layer
I
B No Home Interface
E Generic Session interface is provided for persistence operations
R May write own DAO
N
A No method-level transactions for entities
T Rather emphasize transactions at the business level
E
Truly object-oriented
Polymorphic associations and queries
Three inheritance mapping strategies

[9]
What is HIBERNATE ??

Hibernate is an object-relational mapping (ORM) library for the Java


language, providing a framework for mapping an object-oriented domain
H model to a traditional relational database.
I
B Hibernate solves Object-Relational impedance mismatch problems by
E replacing direct persistence-related database accesses with high-level
R object handling functions.
N
A
T
E

[10]
What is HIBERNATE ??
Its an ORM tool.

Supports Data retrieval and update


H
Transaction management
I
B Database connection pooling
E
R Programmatic as well as declarative queries
N
Declarative entity relationship management
A
T Provides support for collections and object relations
E
Supports numerous databases, including Oracle and DB2

Improved Performance

[11]
Features of Hibernate
Integrates elegantly with all popular J2EE application servers, Web
containers and in standalone applications.

H Support fine grained Object model


I
Transparent Persistence(No build time bye code enhancement)
B
E Free/open source.
R
N Natural programming model.
A
Database independent.
T
E The query language.

[12]
Architecture of Hibernate
A (very) high-level view of the Hibernate architecture:

H
I
B
E
R
N
A
T
E

[13]
Components of Hibernate Architecture

Connection management:
Connection management service provide efficient management of the database
connections. Database connection is the most expensive part of interacting with the
H database as it requires a lot of resources of open and close the database connection.
I
B Transaction Management:
E Transaction management service provide the ability to the user to execute more
R than one database statements at a time.
N
A
Object Relational Mapping:
T
Object relational mapping is technique of mapping the data representation from an
E object model to a relational data model. This part of the hibernate is used to select, insert,
update and delete the records form the underlying table.

[14]
Lite Architecture
It is called "Lite" architecture when we only uses the object relational mapping
component.

H
I
B
E
R
N
A
T
E

[15]
Full Cream Architecture
In "Full Cream" architecture all the three component Object Relational mapping,
Connection Management and Transaction Management) are used.

H
I
B
E
R
N
A
T
E

[16]
The Persistence Life-Cycle
An instance of a persistent class may be in one of three different states, which are
defined with respect to a persistence context. The Hibernate Session object is the
persistence context:

H transient
I The instance is not, and has never been associated with any persistence context. It has no persistent
identity(primary key value).
B
E persistent
R The instance is currently associated with a persistence context. It has a persistent identity (primary
N key value) and, perhaps, a corresponding row in the database. For a particular persistence context,
Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of
A the object).
T
E detached
The instance was once associated with a persistence context, but that context was closed, or the
instance was serialized to another process. It has a persistent identity and, perhaps, a corresponding
row in the database. For detached instances, Hibernate makes no guarantees about the relationship between
persistent identity and Java identity.

[17]
The Persistence Life-Cycle

H
I
B
E
R
N
A
T
E

[18]
Core Interfaces in Hibernate
Session interface

Session interface is primary interface use by hibernate applications.

An instance of session is lightweight and inexpensive to create and destroy.


H
I not thread safe
B
E SessionFactory interface
R Application get instance of session from SessionFactory .
N
A Not light weighted.
T
Thread safe
E
Single session factory for whole application

If application access multiple database then for one database one session factory.

[19]
Core Interfaces in Hibernate
Configuration interface
Application get instance of SessionFactory from Configuration .
Configuration Object is use to configure and bootstrap hibernate.
Application use configuration instance to specify the location of mapping docs and hibernate
H specific properties.
I
B Transaction interface
E Application get an instance of Transaction from Session.
R
N Transaction abstract application code from underlying transaction implementation i.e.
A (JDBC,JTA,CORBA transaction)
T
Query and Criteria interface
E
The query interface allowed you to perform queries against the database and control how the
query is executed.

Criteria interface allow user to create and execute object oriented criteria Queries.

[20]
What is ORM?

Object-relational mapping is a programming technique for converting


data between incompatible type systems in relational databases and object-
H oriented programming languages.
I
B This creates, in effect, a "virtual object database" which can be used from
E within the programming language. There are both free and commercial
R packages available that perform object-relational mapping, although some
N programmers opt to create their own ORM tools.
A
T
E

[21]
What is ORM?
(Cont..)
Object relation mapping is the automated persistence of objects in

java application to the table in a relational database, using metadata

H that describe mapping between object and the database.


I
B
E
R Using ORM we can not only store Entire object graph in database
N
A but also retrieve same as and when required.
T
E
ORM help us to Bridge gap between two different paradigms.

[22]
Feature of ORM

Productivity
H
I Maintainability
B
E Performance
R
N
A Vendor independence
T
E Flexible mapping

[23]
How to configure 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>
H <session-factory>

I <property
name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
B <property
E name="connection.url">jdbc:microsoft:sqlserver://10.7.100.146:143;databasename=YashTraining</
property>
R <property name="connection.username">trainingyash</property>
<property name="connection.password">trainingyash</property>
N <!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
A <property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
T <!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
E <!create-drop,create,update the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="HighScore.hbm.xml"/>
<mapping resource="GameScore.hbm.xml"/>

</session-factory>
</hibernate-configuration>

[24]
Hibernate JDBC Properties

Property name Purpose

H hibernate.connection.driver_class jdbc driver class

I
B hibernate.connection.url jdbc URL
E
R
N hibernate.connection.username database user

A
T hibernate.connection.password database user password
E
hibernate.connection.pool_size maximum number of pooled connections

[25]
Hibernate Datasource Properties
For use inside an application server, Hibernate may obtain connections from a javax.sql.Datasource registered
in JNDI.

Set the following properties

H Property name Purpose


I
B hibernate.connection.datasource datasource JNDI name
E
R
hibernate.jndi.url URL of the JNDI provider (optional)
N
A
T hibernate.jndi.class class of the JNDI InitialContextFactory (optional)

E
hibernate.connection.username database user (optional)

hibernate.connection.password database user password (optional)

[26]
Programmatic Configuration of Hibernate

Creating SessionFactory
Configuration cfg = new Configuration();
cfg.addResource("hello/Message.hbm.xml");
H cfg.setProperties( System.getProperties() );
SessionFactory sessions = cfg.buildSessionFactory();
I Alternate approach to load mapping file is to load classes by calling addClass(class name) method.
B
E SessionFactory sessions = new Configuration()
.addClass(org.hibernate.auction.model.Item.class)
R .addClass(org.hibernate.auction.model.Category.class)
.addClass(org.hibernate.auction.model.Bid.class)
N .setProperties( System.getProperties() )
.buildSessionFactory();
A
T The addClass() method assumes that the name of the mapping file ends with the .hbm.xml extension and is deployed along with the
mapped class file.
E
We can connect to multiple database through hibernate by creating separate instance of SessionFactory through the following
way.
SessionFactory sessions = new Configuration()
.configure("/hibernate-config/auction.cfg.xml")
.buildSessionFactory();

[27]
Basic jar file which is required to run hibernate
+ lib

antlr.jar

cglib-full.jar
H
asm.jar
I
B asm-attrs.jar
E
commons-collections.jar
R
N commons-logging.jar
A hibernate3.jar
T
jta.jar
E
dom4j.jar

log4j.jar

and Database Driver.jar


[28]
Writing POJO (Plain old java object) Point to remember while writing POJO.

POJO class must implements serializable interface. (optional)


-- when objects are stored in an HttpSessionor passed by value using RMI, serialization is necessary.

H No argument constructor must be their.


-- All persistent classes must have a default constructor (which may be nonpublic) so Hibernate can instantiate
I them using Constructor.newInstance().
B
E
Declares accessor/mutator methods for all its persistent fields.
R
N
Provide identifier property. (optional)
A -- identifier property map to primary key column of a database.it can be any primitive type or wrapper type.it Is
T optional however certain functionality of hibernate only support to class which declare identifier prop. Like
session.saveOrUpdate(), session.merge(), transitive reattachment of detached object.
E

Prefer non-final classes (optional)


-- if declared class is final or the methods in that class final then some functionality of hibernate like lazy loading
can not be achieved.

[29]
Basic of O/R mapping
Hibernate-mapping
<hibernate-mapping
schema="schemaName" (1)
catalog="catalogName" (2)
default-cascade="cascade_style" (3)
H default-access="field|property|ClassName" (4)
I default-lazy="true|false" (5)
auto-import="true|false" (6)
B package="package.name" (7)
/>
E
(1) schema (optional): The name of a database schema.
R
(2) catalog (optional): The name of a database catalog.
N
(3) default-cascade (optional - defaults to none): A default cascade style.
A
(4) default-access (optional - defaults to property): The strategy Hibernate should use for accessing all
T
(5) default-lazy (optional - defaults to true): The default value for unspecified lazy attributes of class and collection
E
mappings.
(6) auto-import (optional - defaults to true): Specifies whether we can use unqualified class names (of classes in this
mapping) in the query language.
(7) package (optional): Specifies a package prefix to assume for unqualified class names in the mapping document.
[30]
Basic of O/R mapping
Class
<class
name="ClassName" (1)
table="tableName" (2)
discriminator-value="discriminator_value" (3)
mutable="true|false" (4)
H schema="owner" (5)
I catalog="catalog" (6)
dynamic-update="true|false" (7)
B dynamic-insert="true|false" (8)
lazy="true|false" (9)
E />
R (1) name (optional): The fully qualified Java class name of the persistent class (or interface). If this attribute is missing, it is assumed that the
mapping is for a non-POJO entity.
N (2) table (optional - defaults to the unqualified class name): The name of its database table.
A (3) discriminator-value (optional - defaults to the class name): A value that distinguishes individual subclasses, used for polymorphic
behavior. Acceptable values include null and not null.
T (4) mutable (optional, defaults to true): Specifies that instances of the class are (not) mutable.
E (5) schema (optional): Override the schema name specified by the root <hibernate-mapping> element.
(6) catalog (optional): Override the catalog name specified by the root <hibernate-mapping> element.
(7) dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those
columns whose values have changed.
(8) dynamic-insert (optional, defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns
whose values are not null.
(9) lazy (optional): Lazy fetching may be completely disabled by setting lazy="false".

[31]
Basic of O/R mapping
Id
<id
name="propertyName" (1)
type="typename" (2)
column="column_name" (3)
unsaved-value="null|any|none|undefined|id_value> (4)
H <generator class="generatorClass"/>
I </id>

B
(1) name (optional): The name of the identifier property.
E
R (2) type (optional): A name that indicates the Hibernate type.
N
(3) column (optional - defaults to the property name): The name of the primary key column.
A
T (4) unsaved-value (optional - defaults to a "sensible" value): An identifier property value that indicates that an instance is

E newly instantiated (unsaved), distinguishing it from detached instances that were saved or loaded in a previous session.

[32]
Basic of O/R mapping
Generator
The optional <generator> child element names a Java class used to generate unique
identifiers for instances of the persistent class.
<generator class=hilo>
<param name="table">uid_table</param>
<param name="column">next_hi_value_column</param>
H </generator>
I If any parameters are required to configure or initialize the generator instance, they are passed using the
B <param> element.
E generator class value can be
hilo,
R seqhilo,
N identity,
A sequence,
increment,
T uuid,
E guid,
native,
assigned,

foreign

[33]
Basic of O/R mapping
property
<property
name="propertyName" (1)
column="column_name" (2)
type="typename" (3)
update="true|false" (4)
H insert="true|false" (4)
formula="arbitrary SQL expression" (5)
I lazy="true|false" (6)
unique="true|false" (7)
B not-null="true|false" (8)
E />
(1) name: the name of the property, with an initial lowercase letter.
R (2) column (optional - defaults to the property name): the name of the mapped database table column. This may also be specified by nested
N <column> element(s).
A (3) type (optional): a name that indicates the Hibernate type.
T (4) update, insert (optional - defaults to true) : specifies that the mapped columns should be included in SQL UPDATE and/or INSERT

E statements. Setting both to false allows a pure "derived"


(5) formula (optional): an SQL expression that defines the value for a computed property. Computed properties do not have a column
mapping of their own.lazy (optional - defaults to false): Specifies that this property should be fetched lazily when the instance variable is
first accessed (requires build-time bytecode instrumentation).
(6) unique (optional): Enable the DDL generation of a unique constraint for the columns. Also, allow this to be the target of a property-ref.
(7) not-null (optional): Enable the DDL generation of a nullability constraint for the columns.
[34]
Type of mapping supported by Hibernate

Inheritance mapping
H
I Component mapping
B
E Association mapping
R
N Collection mapping
A
T
E

[35]
Inheritance Mapping

The Three Strategies


Hibernate supports the three basic inheritance mapping strategies:
H
table per class hierarchy
I
B table per subclass
E table per concrete class
R In addition, Hibernate supports a fourth, slightly different kind of
N polymorphism:
A
T implicit polymorphism
E

[36]
Inheritance Mapping
Table Per class Hierarchy

Enable polymorphism by denormalizing the relational model and using a type discriminator column to hold type information
Suppose we have an interface Payment, with implementers CreditCardPayment, CashPayment, ChequePayment.
<class name="Payment" table="PAYMENT" discriminator-value="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
H <generator class="native"/>
</id>
I <discriminator column="PAYMENT_TYPE" type="string"/>
B <property name="amount" column="AMOUNT"/>
...
E <subclass name="CreditCardPayment" discriminator-value="CREDIT">
<property name="creditCardType" column="CCTYPE"/>
R ...
N </subclass>
<subclass name="CashPayment" discriminator-value="CASH">
A <property name="currencyType" column=" CURRENCY_TYPE "/>
...
T </subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
E <property name="chequeNumber" column=" CHEQUE_NO "/>
...
</subclass>
</class>
Exactly one table is required. There is one big limitation of this mapping strategy: columns declared by the subclasses, such as
CCTYPE, may not have NOT NULL constraints.

[37]
Inheritance Mapping
Table Structure (Payment)

Payment_ID Payment_Amount Credit_Card_Type Currency_Type Cheque_No Paym


ent_ty
pe
H
I 1 10000 Null Null Null PAYM
B ENT

E
R 1 10000 10001 Null Null CRED
IT
N
A 1 10000 Null RS Null CASH
T
E 1 10000 Null Null 1234 CHEQ
UE

[38]
Inheritance Mapping
Table Per Subclass
Represent is a (inheritance) relationships as has a (foreign key) relationships
A table per subclass mapping would look like:
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
H </id>
<generator class="native"/>

I <property name="amount" column="AMOUNT"/>


...
B <joined-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
E <property name="creditCardType" column="CCTYPE"/>
R ...
</joined-subclass>
N <joined-subclass name="CashPayment" table="CASH_PAYMENT">
<key column="PAYMENT_ID"/>
A <property name="currencyType" column="CURRENCY_TYPE"/>
T ...
</joined-subclass>
E <joined-subclass name="ChequePayment" table="CHEQUE_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="chequeNo column="CHEQUE_NO"/>
</joined-subclass>
</class>
Four tables are required. The three-subclass tables have primary key associations to the super class table (so the\relational model is
actually a one-to-one association).

[39]
Inheritance Mapping
Payment
Paymemt_id Payment_Amount
1 10000
2 30000
3 2000
H
I
B
Credit_Payment Credit_Card_no Paymemt_id
E
1001 2
R
N
A Cash_Payment Currency_id Paymemt_id

T Rs 1

E
Cheque_Payment Cheque_no Paymemt_id

2345 3

[40]
Inheritance Mapping
Table per concrete class
Discard polymorphism and inheritance relationships completely from the relational model
The following are the mapping for Table per Concrete Class
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
H </id>
<generator class="native"/>

I <property name="amount" column="AMOUNT"/>


...
B <union-subclass name="CreditCardPayment" table="CREDIT_PAYMENT">
E <property name="creditCardType" column="CCTYPE"/>
...
R </union-subclass>
<union-subclass name="CashPayment" table="CASH_PAYMENT">
N <property name="currencyType" column="CURRENCY_TYPE"/>
A ...
</union -subclass>
T <union -subclass name="ChequePayment" table="CHEQUE_PAYMENT">
<property name="chequeNo column="CHEQUE_NO"/>
E
</union -subclass>
</class>

Three tables are involved. Each table defines columns for all properties of the class, including inherited properties.

[41]
Inheritance Mapping
Credit_Card_no Paymemt_id Payment_Amount
Credit_Payment
1001 2 10000

H Cash_Payment Currency_id Paymemt_id Payment_Amount


I Rs 1 2000
B
E Cheque_Payment Cheque_no Paymemt_id Payment_Amount
R 2345 3 5000
N
A limitation of this approach
T If a property is mapped on the superclass, the column name must be the same on all subclass tables.
E
The identity generator strategy is not allowed in union subclass inheritance, indeed the primary key seed has
to be shared accross all unioned subclasses of a hierarchy.

It doesnt support polymorphism.

[42]
Component Mapping
Dependent objects
A component is a contained object that is persisted as a value type, not an entity reference. The term "component" refers to the object-
oriented notion of composition

class Person.java
public class Person {
H private java.util.Date birthday;
I private Name name;
private Set personQualification =new HashSet();
B private Set personEmailAddresses=new HashSet();
private int id;
E }
R class Name.java
N public class Name {
char initial;
A String first;
T }
String last;

E
class PersonQualification .java
public class PersonQualification {
private String collegeStudied = null;
private String qualification = null;
}

[43]
Component Mapping
Now Name may be persisted as a component of Person.Notice that doesn't need to declare any or identifier properties.

<class name="com.yash.hibernate.Person" table="person">


<id name="id" column="pid" type="int">
<generator class="increment"/>
</id>
H <property name="birthday" type="date"/>
I <component name="Name" class="com.yash.hibernate.Name"> <!-- class
attribute optional -->
B <parent name="namedPerson not-null=true/>
<property name="initial not-null=true/>
E <property name="first not-null=true/>
R <property name="last not-null=true/>
</component>
N </class>

A The person table would have the columns pid, birthday, initial, first and last.
T properties of a component may be of any Hibernate type (collections, many-to-one associations, other components etc)
E
The <component> element allows a <parent> subelement that maps a property of the component class as a reference back to the
containing entity.

[44]
Component Mapping
Collections of dependent objects
Collections of components are supported. Declare your component collection by replacing the <element> tag with a <composite-element>
tag.
<set name="personQualifications" table="PersonQualifications" lazy="true">
<key column="id"/>
<composite-element class="com.yash.hibernate.PersonQualification"> <!-- class attribute required -->
H <property name="collegeStudied not-null=true/>
I <property name="qualification not-null=true/>
</composite-element>
B </set>
<set name="emailAddresses" table="PersonEmailAddresses">
E <key column="id" not-null="true"/>
R </set>
<element type="string" column="EMAIL_ADDRESS not-null=true/>

N
A Composite elements may contain components but not collections. If your composite element itself contains components, use the
T <nested-composite-element> tag.

E Limitation of component mapping

-- Shared references arent possible.


-- There is no elegant way to represent a null reference to an Address.

[45]
Association Mapping

Association

H
I
B Unidirectional Bi-Directional
E
R
N Many to
One
A Many Many One
To
One Many One
To To To -------- To
T Many To
Many One One One to Many One
E Many

[46]
Unidirectional Association Mapping (Many to One)

<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
H </id>
<many-to-one name=address column=addressId not-null=true />
I </class>

B <class name="Address">
E <id name=id column=addressId>
<generator class=native />
R </id>
</class>
N
A
Created Table Structure
T
E create table Person ( personId bigint not null primary key, addressId bigint not null )

create table Address ( addressId bigint not null primary key )

[47]
Unidirectional Association Mapping (One to One)

A unidirectional one-to-one association on a foreign key is almost identical. The only difference is the column (unique constraint.)

<class name="Person">
<id name=id column=personId>
<generator class=native />
H </id>
<many-to-one name=address column=addressId unique=true not-null=true />
I </class>
B <class name="Address">
E <id name=id column=addressId>
<generator class=native />
R </id>
N </class>

A
Created Table Structure
T
E create table Person ( personId bigint not null primary key, addressId bigint not null unique )

create table Address ( addressId bigint not null primary key )

[48]
Unidirectional Association Mapping (One to Many)

<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
H <set name="addresses">
<key column="personId not-null="true"/>
I <one-to-many class="Address"/>
B </class>
</set>

E <class name="Address">
<id name="id" column="addressId">
R <generator class="native"/>
N </class>
</id>

A
T
E Created Table Structure

create table Person ( personId bigint not null primary key )


create table Address ( addressId bigint not null primary key, personId bigint not null references
person(personId))

[49]
Unidirectional Association Mapping (Many to Many)

<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<set name="addresses" table="PersonAddress">
H <key column="personId"/>
<many-to-many column="addressId class="Address"/>
I </set>
B </class>
<class name="Address">
E <id name="id" column="addressId">
<generator class="native"/>
R </id>
N </class>

A Created Table Structure


T create table Person ( personId bigint not null primary key )
E create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId))
create table Address ( addressId bigint not null primary key )

[50]
Bi-directional Association Mapping

A bidirectional association allows navigation from both "ends" of the


association. Two kinds of bidirectional association are supported:
H
I
B
one-to-many/many-to-one
E set or bag valued at one end, single-valued at the other
R many-to-many
N set or bag valued at both ends
A
T
E

[51]
Bi-directional Association Mapping (One to Many / Many to One)
A bidirectional many-to-one association is the most common kind of association. (This is the standard parent/child relationship.)

<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
H <set name="address" inverse="true">
<key column="personId"/>
I <one-to-many class="address"/>
B </class>
</set>

E <class name="Address">
<id name="id" column="addressId">
R <generator class="native"/>
N </id>
<many-to-one name="person column="personId not-null="true"/>
A </class>

T
E
create table Person ( personId bigint not null primary key )

create table Address ( addressId bigint not null primary key, personId references(person) );

[52]
Bi-directional Association Mapping (Many to Many)
<class name="Person">
<id name="id" column="personId">
<generator class="native"/>
</id>
<set name="addresses">
<key column="personId"/>
H </set>
<many-to-many column="addressId class="Address"/>

I </class>
<class name="Address">
B <id name="id" column="addressId">
E </id>
<generator class="native"/>

R <set name="people" inverse="true">


<key column="addressId"/>
N <many-to-many column="personId class="Person"/>
A </class>
</set>

T
E create table Person ( personId bigint not null primary key )

create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key
(personId,addressed))

create table Address ( addressId bigint not null primary key )


[53]
Bi-directional Association Mapping (One to One)
one-to-one only applies to the shared primary key approach and that when you want to
use the foreign key approach you have to use many-to-one. with a unique constraint.

<class name="Person">
<id name="id" column="personId">
H <generator class="native"/>
I </id>
<many-to-one name="address column="addressId unique="true not-null="true"/>
B </class>
<class name="Address">
E <id name="id" column="addressId">
R </id>
<generator class="native"/>

N <one-to-one name="person property-ref="address"/>


</class>
A
T
E
create table Person ( personId bigint not null primary key, addressId bigint not null unique )

create table Address ( addressId bigint not null primary key )

[54]
Bi-directional Association Mapping (One to One)

on primary key using special id generator

foreign: uses the identifier of another associated object. Usually used in conjunction
with a <one-to-one> primary key association.
H
I <class name="Person">
<id name="id" column="personId">
B <generator class="native"/>
</id>
E <one-to-one name="address"/>
R </class>
<class name="Address">
N <id name="id" column="personId">
<generator class="foreign">
A <param name="property">person</param>
T </id>
</generator>

E <one-to-one name="person constrained="true"/>


</class>

create table Person ( personId bigint not null primary key )


create table Address ( personId bigint not null primary key )

[55]
Collection Mapping
Hibernate Map Collections as value type and required persistent collection valued fields be
declared as an interface type.

H Hibernate support followingMapping


mapping of Set
I
B Mapping of idBag
E
R Mapping of List
N
A Mapping of Map
T
E
Following are the attribute which are common for all mapping element like
<set>, <map>, <list>, <idbag>.

[56]
Collection Mapping
<map
name=propertyName (1)
table=table_name (2)
schema=schema_name (3)
lazy=true|false (4)
inverse=true|false (5)
H cascade=all|none|save-update|delete|all-delete-orphan (6)
sort=unsorted|natural|comparatorClass (7)
I order-by=column_name asc|desc (8)
optimistic-lock=true|false (9)
B >
E <key . />
<map-key . />
R <element . />
</map>
N (1) name the collection property name
A (2) table (optional defaults to property name) the name of the collection table (not used for one-to-many associations)
(3) schema (optional) the name of a table schema to override the schema declared on the root element
T (4) lazy (optional defaults to true) may be used to disable lazy fetching and specify that the association is always eagerly fetched (not
available for arrays)
E (5) inverse (optional defaults to false) mark this collection as the inverse end of a i-directional association
(6) cascade (optional defaults to none) enable operations to cascade to child entities
(7) sort (optional) specify a sorted collection with natural sort order, or a given comparator class
(8) order-by (optional, JDK1.4 only) specify a table column (or columns) that define the iteration order of the Map, Set or bag but not list,
together with an optional asc or desc
(9) access (optional defaults to property): The strategy Hibernate should use for accessing the property value.

[57]
Collection Mapping (Example)
Considering following example for all collection mapping demo

H
I
B
E
R
N
A
T
(Collection of Image components in Item)
E

[58]
Mapping of Set

Point to be remember for set

Set cant contain duplicate element.


H
I Equals () and hashcode () must be override for comparison.
B
For component mapping it is required to override equals() and hashcode() its help
E
R hibernate for dirty checking although it is not mandatory.
N
A Not-null constraint must be true for all the composite elements.
T
E

[59]
Mapping of Set

Mata data for set


<set name="images lazy="true table="ITEM_IMAGE" order-by="IMAGE_NAME asc">
<key column="ITEM_ID"/>
H <composite-element class="src.Image">
I <property name="name" column="IMAGE_NAME" not-null="true"/>
<property name="fileName" column="FILENAME" not-null="true"/>
B <property name="sizeX" column="SIZEX" not-null="true"/>
<property name="sizeY" column="SIZEY" not-null="true"/>
E </composite-element>
R </set>

N
A Table structure
T Item_table(Item_id,Item_name,Item_desc,price)
E Item_Image(Item_id,Image_name,File_Name,SizeX,SizeY)

Item_id of Item_Image is foreign key of item_table

[60]
Mapping of idBag
If your table doesn't have an index column, and you still wish to use List as the property type,

you should map the property as a Hibernate <bag>. A bag does not retain its order when it is

retrieved from the database, but it may be optionally sorted or ordered.


H
I Unordered collection that support duplicate element.
B
E Its just like List but it is unordered.
R
N Composite element can contain null values.
A
Its an hibernate mapping collection mapping type
T
E We can use List in POJO for mapping bag.

<idbag> mapping lets us attach a surrogate key column to the collection table

[61]
Mapping of idBag

<idbag name="images lazy="true table="ITEM_IMAGE order-by="IMAGE_NAME asc">


<collection-id type="int" column="ITEM_IMAGE_ID">
<generator class="native"/>
</collection-id>
<key column="ITEM_ID"/>
H <composite-element class="src.Image">
I <property name="name" column="IMAGE_NAME"/>
<property name="fileName" column="FILENAME" not-null="true"/>
B <property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>
E </composite-element>
R </idbag>

N
A Table structure
T
Item_table(Item_id,Item_name,Item_desc,price)
E Item_Image(Item_image_id,Item_id,Image_name,File_Name,SizeX,SizeY)

Item_id of Item_Image is foreign key of item_table

[62]
Mapping of List

Ordered collection that support duplicate element.

H Required the addition of an index column to database table .Index column define position of
I
B element in collection.
E
R List doesnt support order-by attribute.
N
A
T
E

[63]
Mapping of List
Metadata of List

<list name="images" lazy="true" table="ITEM_IMAGE">


<key column="ITEM_ID"/>
<index column="POSITION"/>
H <composite-element class="src.Image">
I <property name="name" column="IMAGE_NAME"/>
<property name="fileName" column="FILENAME" not-null="true"/>
B <property name="sizeX" column="SIZEX"/>
<property name="sizeY" column="SIZEY"/>
E </composite-element>
</list>
R
N
A Table Structure
T
E Item_table(Item_id,Item_name,Item_desc,price)
Item_Image(position,Item_id,Image_name,File_Name,SizeX,SizeY)

Item_id of Item_Image is foreign key of item_table

[64]
Mapping of Map

Store the value in form of key and Value


H
I Key and value both with be going to store in database
B
E Map is an unordered .
R
Map can be sort base on natural order or based on implementation of comparator
N
A Key must be unique but value can be duplicated.
T
E

[65]
Mapping of Map
Meta data for Map

<map name="images" lazy="true" table="ITEM_IMAGE" sort="src.ImageComparator">


<key column="ITEM_ID"/>
<map-key column="IMAGE_NAME" type="string"/>
H <composite-element class="src.Image">
<property name="fileName" column="FILENAME" not-null="true"/>
I <property name="sizeX" column="SIZEX"/>
B <property name="sizeY" column="SIZEY"/>
</composite-element>
E </map>

R
N Table Structure
A Item_table(Item_id,Item_name,Item_desc,price)
T Item_Image(Item_id,Image_name,File_Name,SizeX,SizeY)
E Item_id of Item_Image is foreign key of item_table
Primary key of Item_image is(item_id,Image_name)
Image_name is key of Map

[66]
H
I
B
E
R
Thanking You!!
N
A
T
E

[67]

You might also like