Welcome To The World of Hibernation - 3.0: H I B E R N A T E
Welcome To The World of Hibernation - 3.0: H I B E R N A T E
Welcome To The World of Hibernation - 3.0: H I B E R N A T E
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?
[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 – There’s 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?
[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 • Can’t 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
[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 ??
[10]
What is HIBERNATE ??
• Its an ORM tool.
• Improved Performance
[11]
Features of Hibernate
[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
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
I specific properties.
B Transaction interface
E
R Application get an instance of Transaction from Session.
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?
[21]
What is ORM?
(Cont..)
Object relation mapping is the automated persistence of objects in
[22]
Feature of ORM
H Productivity
I
B Maintainability
E
R
N
Performance
A
T Vendor independence
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>
<session-factory>
H
I <property
name="connection.driver_class">com.microsoft.jdbc.sqlserver.SQLServerDriver</property>
B <property
name="connection.url">jdbc:microsoft:sqlserver://10.7.100.146:143;databasename=YashTraining</
E 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
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.
E
hibernate.connection.username database user (optional)
[26]
Programmatic Configuration of Hibernate
Creating SessionFactory
Configuration cfg = new Configuration();
cfg.addResource("hello/Message.hbm.xml");
cfg.setProperties( System.getProperties() );
H SessionFactory sessions = cfg.buildSessionFactory();
I
Alternate approach to load mapping file is to load classes by calling addClass(class name) method.
B
SessionFactory sessions = new Configuration()
E .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
[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"/>
</id>
I
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.
generator class value can be
E 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
H Inheritance mapping
I
B Component mapping
E
R Association mapping
N
A Collection mapping
T
E
[35]
Inheritance Mapping
[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"/>
<property name="amount" column="AMOUNT"/>
B ...
E <subclass name="CreditCardPayment" discriminator-value="CREDIT">
<property name="creditCardType" column="CCTYPE"/>
R ...
</subclass>
N <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)
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">
<generator class="native"/>
H </id>
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"/>
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
[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 attribute optional -->
<component name="Name" class="com.yash.hibernate.Name"> <!-- class
[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
[45]
Association Mapping
Association
H
I
B Unidirectional Bi-Directional
E
R
N Many to
Many Many One One One
A To
One Many
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 )
[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
[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>
[50]
Bi-directional Association Mapping
[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"/>
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))
<class name="Person">
<id name="id" column="personId">
H <generator class="native"/>
</id>
I <many-to-one name="address“ column="addressId“ unique="true“ not-null="true"/>
B </class>
<class name="Address">
E <id name="id" column="addressId">
<generator class="native"/>
R </id>
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 )
[54]
Bi-directional Association Mapping (One to One)
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>
[55]
Collection Mapping
Hibernate Map Collections as value type and required persistent collection valued fields be
declared as an interface type.
[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
[59]
Mapping of 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)
[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
• <idbag> mapping lets us attach a surrogate key column to the collection table
[61]
Mapping of idBag
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
[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">
<property name="name" column="IMAGE_NAME"/>
I <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
[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"/>
<property name="sizeY" column="SIZEY"/>
B </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]