- Relational Persistence for Java and
. NET
Historically, Hibernate facilitated the storage and retrieval of Java domain objects via Object/Relational Mapping. Today, Hibernate is a collection of related projects enabling developers to
http://www.hibernate.org/
Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate
Hibernate is free software that
http://en.wikipedia.org/wiki/Hibernate_%28Java%29
- Component
Refers to the UML modeling term
composition
Commonly referred to as a “has a”
– An
Does not exist on its own;
on a parent object
• Address is a component of ‘
– Non-existent without
– No id of its own
Entity
lives on its own
Can
Can
‘
– Can
– Has its own id
Using Components
1. Determine your domain model
Which objects are best suited to be a component?
2. Create your database tables
Model your components accordingly within entity tables
Create your Java classes
• One for each entity, and one for each component
• Setup your components within the entity classes
Write the Hibernate mapping file for the
entity, using the embedded component tag
Nested Components
Component Address has nested component ‘
Inheritance
Commonly referred to as an “is
relationship
Polymorphism
– Dynamic realization of subclass behavior while
treating the object as an instance of its superclass
Inheritance Realization
Easy to do in an
– Java: Use ‘extends’ or
Not so easy to do in a relational database
– Tables do not ‘extend’ from each other
– Part of the ‘impedance mismatch’ problem
How do we get around this?
– Four approaches through Hibernate
• Hibernate implicit polymorphism
• Table-per-concrete class
• Table-per-class-hierarchy
• Table-per-subclass
Modeling Inheritance
1
What objects have hierarchical relationships?
2. Choose your inheritance strategy
• Hibernate implicit
• Table-per-concrete class
• Table-per-class-hierarchy
• Table-per-
3. Create your database tables based on the
chosen strategy
4. Code your Java objects, using
5. Write your Hibernate mapping file using
the
Implicit Polymorphism
Database
– One database table per concrete class
Hibernate Mapping Files
– Separate mapping files for each inherited class
• Like normal, including any inherited properties
Default Behavior
– Out of the box Hibernate will automatically
recognize any Java inheritance associations
Implicit Polymorphism
Advantages
– Get it for free. Hibernate automatically scans classes
on startup (including inheritance); No additional
configuration/mapping
– Not a lot of
Queries against individual types are fast and simple
Disadvantages
– Makes handling relationships difficult
• One-to-many relationships typically require a foreign key, but
inherited associations can’t
don’t support it (Example:
– Polymorphic queries are process intensive
• For queries against the superclass, Hibernate executes
multiple queries
– SELECT * FROM CHECKING_ACCOUNT WHERE
ACCOUNT_OWNER_ID=?
– SELECT * FROM SAVINGS_ACCOUNT WHERE
ACCOUNT_OWNER_ID=?
– Database schema evolution more
• Need to add the same column to multiple tables
• Integrity constraints might have to span multiple tables
Table-per-concrete class
Database
– One database table per concrete class
Hibernate Mapping
– Single mapping
• Based on superclass
• Includes
Table-per-concrete class
• Advantages
Shared mapping of common elements
• Shared database id
– Not a lot of
– Queries against individual types are fast and simple
–
polymorphic queries
• Disadvantages
– Still have difficulty with relationships
• Foreign keying to two tables not possible
– Database schema evolution still more
• Need to add the same column to multiple tables
• Integrity constraints might have to span multiple tables
Table-per-class-hierarchy
Database
– One database table for all subclasses
–
Hibernate Mapping
– Single mapping file still based on superclass
– Includes
classes
– Use ‘discriminator’ column/field to identity
concrete type
Table-per-class-hierarchy
• Advantages
– Simple
– Fast reads/writes, even across types
• Disadvantages
– Lots of
•
–
database design
Table-per-subclass
Database
– One database table for the superclass AND
one per subclass
• Shared columns in superclass table
• Subclass tables have their object-specific
columns
Hibernate Mapping File• Hibernate Mapping File
– Single mapping file based on the superclass
Includes
inherited classes
Table-per-subclass
• Advantages
– Normalized schema
• Schema evolution and integrity are straight
– Reduced number of SQL statements produced
• Hibernate uses inner joins for subclass queries• Hibernate uses inner joins for subclass queries,
outer joins for polymorphic ones
• Disadvantages
– Can have
• Requires many joins or sequential reads for queries
When to use Which
• Leave implicit polymorphism for queries against interfaces (based on behavior not
attributes
• If you rarely require polymorphic queries, lean towards table-per-concrete-class.
• If polymorphic AND many distinct properties, look
weighing the cost of joins versus unions
Summary
Components
•
• Component are
the different methods of modeling inheritance relationships through Java/Database/Hibernate, and where each one is best
suited
Hibernate implicit polymorphism
• Table-per-concrete class
• Table-per-class-hierarchy
• Table-per-subclass
04-hibernate-
http://courses.coreservlets.com/Course-Materials/hibernate.html
- Relationship Types
Association
– Mapping relationships between two objects
– Example
• Account and
• Collection• Collection
– Collection of values representing individual
pieces of data
– Example
• Map of holidays
• String array of months
Relationship Dimensions
Relationships between entities can
exist in multiple ways
– Multiplicity
• How many on each side of the
– Directionality
• From which side
you access the other?
Relationship Multiplicity
One-to-Many
– Reverse of a many-to-one relationship
• Many-to-Oney
– Multiple Transactions belong to a single account
– Reverse of a one-to-many relationship
One to One• One-to-One
– A single
– A single
• Many-to-Many
– Multiple Accounts have multiple
Oft li d
• A single Account has multiple
• A single
Relationship Directionality
Unidirectional
Cl
relationship
– Example: Account
• Given an Account object, can
Transaction objects.
• Given a Transaction object, cannot
Account object.
• Bidirectional
– Can traverse objects from both sides of the
– Example: Account
• Given an Account object, can
Transaction
• Given a Transaction object, can
Account object
Java vs. Database
Objects are inherently directional
• An object has a reference/pointer to another
object
– Transition by walking a networked graph of
object references
Database
– Relations are not inherently directional
A
columns of other tables
to)
– Transition by joining tables together through
joins/foreign keys
Relationships in Database
• Record repeated in same table each time capturing• Record repeated in same table, each time capturing
different relationship data.
– Foreign keys
• Follow identifiers to related records on other tables
– Join tables
• Tables specifically setup to maintain a relationship
between two identities (usually for M
–
• Arbitrary joins between columns relating data
Relationships in Java
For ‘Many’ side, Collections API
– Set
• No duplication allowed• No duplication allowed
• Objects organized with or without order
– Map
• Duplicate values allowed using different
• Can
– List
• Duplication
• Objects expected to
– Arrays
• Duplication allowed
• Objects expected to
• Strongly typed to
Relationships in Database
P
•
• Easy to query against
– Cons
• Contains redundant data
• Requires many
Foreign Keys
P
• Reduce redundancy
• Better modeling of data
– Cons
• Slower than
• Slightly more complicated to query against
Join Tables
Pros
• Built on foreign key model, enables
– Cons
• Slower yet and even more complex querying
Joins
– Pros
• Allows for any
to
C
• No model enforcement
– Can join ‘age’ and ‘office floor’ columns
• Can
as desired
Java-to-Database Through Hibernate
Association & Collection mapping tags practically identical
Hibernate Collection Types
-<set>
• Unordered/Ordered, requiring value column
– <map>
• Unordered/Ordered, requiring key and value
– <list>
Ordered requiring an index column on the• Ordered, requiring an index column on the
referenced object table
– <array>
• Map to Java Type and Primitive Arrays• Map to Java Type and Primitive Arrays
• Ordered, requiring an index column on the
referenced object table
– <bag>
• No direct implementation available in Java
• Unordered/ordered collection allowing
• Realized through Collection/List
• Requires value column
• Used for many-to-many relationships
• Same as Bag but with
column used for surrogate keys
• Requires an ID Generator just like Entity classes
03-hibernate-
http://courses.coreservlets.com/Course-Materials/hibernate.html
- Building a Hibernate Application
Define the domain model
2. Setup your Hibernate configuration
– hibernate.cfg.xml
3 C
– <
4 Make Hibernate aware of the mapping files4. Make Hibernate aware of the mapping files
– Update the hibernate.cfg.xml with
5 Implement a HibernateUtil class5. Implement a HibernateUtil class
– Usually taken from the Hibernate documentation
6. Write your code
02-hibernate-
http://courses.coreservlets.com/Course-Materials/hibernate.html
- N-Tier Architecture
– Each layer encapsulates specific responsibilities
– Enables changes in one area with minimal impact to other
areas of the
• Common tiers
– Presentation
• ‘View’ in model-view-controller
• Responsible for displaying data only. No business logic
Service
• Responsible for business logic
– Persistence
• Responsible for storing/retrieving data
01-hibernate-
http://courses.coreservlets.com/Course-Materials/hibernate.html
- impedance mismatch
The object-relational impedance mismatch is a set of conceptual and technical difficulties that
Mismatches
Object-oriented concepts
Encapsulation
Object-oriented programs
Accessibility
In relational thinking, "private" versus "public" access is relative to need rather than being an absolute characteristic of the data's state, as in the OO model. The relational and OO models often have conflicts over relativity versus absolutism of classifications and characteristics.
Interface, class, inheritance and polymorphism
essential OOP concepts for classes of objects, inheritance and polymorphism
Mapping to relational concepts
Data type differences
A major mismatch between existing relational and OO languages is the type system differences. The relational model strictly prohibits by-reference attributes (or pointers), whereas OO languages embrace and expect by-reference behavior. Scalar types and their operator semantics are also
For example, most SQL systems support string types with varying collations and constrained maximum lengths (open-ended text types
Structural and integrity differences
Another mismatch has to do with the differences in the structural and integrity aspects of the contrasted models. In OO languages, objects can
Manipulative differences
The relational model has an intrinsic, relatively small and well defined set of primitive operators for usage in the query and manipulation of data, whereas OO languages
Transactional differences
relational database transactions, as the smallest unit of work performed by databases, are much larger than any operations performed by classes in OO languages
Solving impedance mismatch
Minimization
There have been
Alternative architectures
The rise of XML databases and XML client structures has motivated other alternative architectures to get around the impedance mismatch challenges. These architectures use XML technology in the client (such as
http://en.wikipedia.org/wiki/Objecwt-relational_impedance_mismatch
- Inheritance is one of the most visible facets of Object-relational mismatch.
Object oriented systems can model both “is a” and “has a” relationship. Relational model supports only “has a” relationship between two entities. Hibernate can help you map such Objects with relational tables. But you need to choose certain mapping strategy based on your needs.
1. Map one table per concrete class. Your mapping ignores the inheritance relationship and maps one table per concrete class. (implicit polymorphism)
2. Map one table per concrete class with union-subclass mapping. You still have one table per concrete class, but you use a “union-subclass” clause in your mapping. This helps mitigate
3. Map one table per class hierarchy. Here your table will have a row for all the fields in the full class hierarchy. You will have a lot of potential null values and you will have a discriminator column to hold type information.
4. Map one table per subclass. Here you convert the
http://simsonlive.
- inheritance models in Hibernate and describes how they work like vertical inheritance and horizontal
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass
(omitting implicit polymorphism which is table per concrete class)
Example:
Let us take the simple example of 3 java classes.
Class
1. Table per concrete class with unions
Tables:
2. Table per class hierarchy
There will be only one table in
But it needs some discriminating column to differentiate between
3. Table per subclass
There are three
Single Table Strategy,
With Table Per Class Strategy,
With Joined Strategy
http://www.dineshonjava.com/p/implementing-inheritance-in-hibernate.html#
- There can be three kinds of inheritance mapping in hibernate
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass
Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and
1. Table per concrete class with unions
In this
Tables: Car,
2. Table per class hierarchy
There will be only one table in
Here it
3. Table per subclass
http://www.interviewjava.com/2007/10/explain-different-inheritance-mapping.html
- Hibernate Object Lifecycle
hibernate considers objects it can
states
Transient
– Persistent
– Removed
– Detached
Transient State
All objects start off in the transient
– Account account = new Account
• account is a transient object
Hibernate is not aware of the object
instance
Persistent State
Hibernate
This is the only state where objects
database
Persistent State
Session session =
// ‘transient’ state
Account account = new Account
// transition to the ‘persistent’ state. Hibernate is NOW
// aware of the object and will save it to the
session
// modification of the object will automatically
// saved because the object is in the ‘persistent’ state
account
// it
session
Removed State
A previously persistent object that is
deleted from the database
– session
Detached State
A persistent object that is still referenced
after closure of the active sessionafter closure of the active session
– session.close() changes object’s state from persisted to
detached
Saving Changes to the Database
Session methods do NOT save changes to
the databasethe database
– save();
– update();p ();
– delete();
These methods actually SCHEDULE
changes to be made to the databasechanges to be made to the database
Hibernate collects SQL statements to be
issued
Statements are later flushed to the database
– Once submitted, modifications to the database are not
permanent until a commit is issuedpermanent until a commit is issued
• session.getTransaction().commit();
Flushing the Context
Submits the stored SQL statements to
th d t bthe database
• Occurs when:
– transaction.commit() is called
– session.flush() is called explicitly
Before a query is executed– Before a query is executed
• If stored statements would affect the results of the quer
Cascading
Hibernate represents domain object
• Propagate the persistence action not only to
the object submitted, but also to any objects
associated with that object
05-hibernate-Object_Lifecycle_Persistence_and_Session_Management
http://courses.coreservlets.com/Course-Materials/hibernate.html
- Transactions
Represents a single unit-of-work
All or nothing – either all of the actions get committed or the entire effort fails
Other resources can also participate in• Other resources can also participate in
transactions
– Java Messaging Service (JMS)gg ( )
• Roll back a message if something fails
– Legacy Systems
– Anything that leverages JTS (Java Transaction Service)
• TransactionManager Interface
- Walked through Query by Criteria (QBC) and Query by
Example (QBE) querying methods, and learned about the
core Hibernate classes involved in querying
• Criteria
• Criterion
• Restrictions
• Property
• Order
• Projections
07-hibernate-Querying_QBC_and_QBE
http://courses.coreservlets.com/Course-Materials/hibernate.html
- three ways of handling inheritance
– Single table per class hierarchy
• InheritanceType.SINGLE_TABLE
Tbl i l– Table per concrete entity class
• InheritanceType.TABLE_PER_CLASS
“join” strategy where fields or properties that are– join strategy, where fields or properties that are
specific to a subclass are mapped to a different
table than the fields or properties that are pp
common to the parent class
• InheritanceType.JOINED
MiiHib t’Iliit• Missing Hibernate’s Implicit
Polymorphism
10-hibernate-JPA.pdf
http://courses.coreservlets.com/Course-Materials/hibernate.html
Hibernate supports various types of connection pooling mechanisms such as C3P0, Apache DBCP, Proxool. C3P0 is an Open source connection pool that comes bundled with hibernate.
http://www.mindfiresolutions.com/How-to-configure-C3P0-connection-pooling-in-Hibernate-1649.php
- What is Connection Pooling? In many of our applications we need to connect to the database for various purposes such as inset, update , delete and retrieve the data from the DB. For each of these activities the application needs to connect to the database which is expensive in terms of resource as well as time. Instead of connecting to the database each time a user makes a request which requires database operation an application should use a pool of connections. Then each application thread that needs to access the database can request a connection from the pool and returns the same to the pool when all the database operations have been executed. This mechanism is called connection pooling.
Hibernate supports various types of connection pooling mechanisms such as C3P0, Apache DBCP, Proxool. C3P0 is an Open source connection pool that comes bundled with hibernate.
http://www.mindfiresolutions.com/How-to-configure-C3P0-connection-pooling-in-Hibernate-1649.php
Nice and Informative Blog.
ReplyDeleteVisit us: Java Online Training
Visit us: Core java training