Tuesday, October 23, 2012

Hibernate



  • 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 utilize POJO-style domain models in their applications in ways extending well beyond Object/Relational Mapping.
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 solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.

Hibernate is free software that is distributed under the GNU Lesser General Public License.
http://en.wikipedia.org/wiki/Hibernate_%28Java%29





  • Component

Refers to the UML modeling term ofRefers to the UML modeling term of
composition
Commonly referred to as a “has a”
relationshipeato s p
– An AccountOwner has an Address
Does not exist on its own; dependentDoes not exist on its own; dependent
on a parent object

Address’ is a component
• Address  is a component of ‘AccountOwner
– Non-existent without AccountOwner
– No id of its own

Entity
lives on its own
Can be made components
Can be related/associated to other entities

AccountOwner’ is an Entity
– Can lives on its own
– 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
ithi it t id tif th t lwithin it to identify the component class


Nested Components
Component  Address  has nested component ‘ZipCode



Inheritance
Commonly referred to as an “is a”Commonly referred to as an  is a
relationship
Polymorphism
– Dynamic realization of subclass behavior while
treating the object as an instance of its superclass


Inheritance Realization
Easy to do in an object oriented language
– Java: Use ‘extends’ or implements’ keyword
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.Determine your domain model
What objects have hierarchical relationships?
2. Choose your inheritance strategy
• Hibernate implicit polymorphismHibernate implicit polymorphism
• Table-per-concrete class
• Table-per-class-hierarchy
• Table-per-subclassTable per subclass
3. Create your database tables based on the
chosen strategy
4. Code your Java objects, using extends’ or
implements’
5. Write your Hibernate mapping file using
the appropriate subclass tags



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 neededconfiguration/mapping needed
– Not a lot of nullable columns (good for integrity)
Queries against individual types are fast and simple– 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 key to both tables; Databases y
don’t support it  (Example:  AccountOwner:Account)
– Polymorphic queries are process intensive
• For queries against the superclass, Hibernate executes o que es aga s e supe c ass, be a e e ecu es
multiple queries
– SELECT * FROM CHECKING_ACCOUNT WHERE
ACCOUNT_OWNER_ID=?
– SELECT * FROM SAVINGS_ACCOUNT WHERE
ACCOUNT_OWNER_ID=?
– Database schema evolution more complexp
• 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 fileg pp g f
• Based on superclass
• Includes union-subclass’ definitions for inherited classes


Table-per-concrete class

• Advantages
Shared mapping of common elements
• Shared database id
– Not a lot of nullable columns (good for integrity)Not a lot of nullable columns (good for integrity)
– Queries against individual types are fast and simple
Less SQL statements generated with use of ‘Union’ for
polymorphic queries
• Disadvantages
– Still have difficulty with relationships
• Foreign keying to two tables not possible
– Database schema evolution still more complexp
• 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
Denormalized table has columns for all attributes

Hibernate Mapping
– Single mapping file still based on superclass
– Includes subclass’ definitions for inherited
classes
– Use ‘discriminator’ column/field to identity
concrete type


Table-per-class-hierarchy
• Advantages
– Simple
– Fast reads/writes, even across types
• Disadvantages
– Lots of nullable columns
Possible data integrity concern
Denormalized table generally considered bad
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 joined subclass’ definitions for– Includes  joined-subclass  definitions for
inherited classes



Table-per-subclass
• Advantages
– Normalized schema
• Schema evolution and integrity are straight
fdforward
– 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 poor performance for complex systems
• Requires many joins or sequential reads for queries



When to use Which
• Leave implicit polymorphism for queries against interfaces (based on behavior not differentinterfaces (based on behavior, not different
attributes)

• If you rarely require polymorphic queries, lean towards table-per-concrete-class.

• If polymorphic behavior is required, AND subclasses have only a few distinct properties, try table-per-l hi hclass-hierarchy

• If polymorphic AND many distinct properties, look atIf polymorphic AND many distinct properties, look at table-per-subclass or table-per-concrete-class,
weighing the cost of joins versus unions



Summary
Components are different from Entities
Enties have their own IDs
• Component are dependant on Entities

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-Component_and_Inheritance_Mapping
http://courses.coreservlets.com/Course-Materials/hibernate.html




  • Relationship Types

Association
– Mapping relationships between two objects
– Example
• Account and AccountOwner
• Collection• Collection
– Collection of values representing individual
pieces of data
– Example
• Map of holidays
• String array of months



Relationship Dimensions

Relationships between entities can p
exist in multiple ways
– Multiplicity
• How many on each side of the
relationship?p
– Directionality
• From which side(s) of the relationship canFrom which side(s) of the relationship can
you access the other?



Relationship Multiplicity


One-to-Many
A il Ath Tti– A single Account has many Transactions
– 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 AccountOwner has a single HomeAddress
– A single HomeAddress has a single AccountOwnerg g
• Many-to-Many
– Multiple Accounts have multiple AccountOwners
Oft li d th h t t lti hi– Often realized through two one-to-many relationships
• A single Account has multiple AccountOwners
• A single AccountOwner has multiple Accounts



Relationship Directionality
Unidirectional
Cl bjf idfh– Can only traverse objects from one side of the
relationship
– Example: Account : Transaction
• Given an Account object, can obtain related
Transaction objects.
• Given a Transaction object, cannot obtain related
Account object.
• Bidirectional
– Can traverse objects from both sides of the relationshipCan traverse objects from both sides of the relationship
– Example: Account : Transaction
• Given an Account object, can obtain related
Transaction objectsTransaction objects.
• Given a Transaction object, can obtain related
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 t bl bit il j i it l ith• A table can arbitrarily join its columns with
columns of other tables (not just those keyed
to)
– Transition by joining tables together through
joins/foreign keys



Relationships in Database
Denormalized table
• 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 pyp p
between two identities (usually for M:M)
Ad hoc joins in a query
• 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 keysDuplicate values allowed, using different keys
• Can be organized with or without order
– List
• Duplication allowedDuplication allowed
• Objects expected to be organized in an order
– Arrays
• Duplication allowed
• Objects expected to be organized in an order
• Strongly typed to particular object type, and lacks ability to resize



Relationships in Database
Denormalized Table
P– Pros
Very fast
• Easy to query against
– Cons
• Contains redundant data
• Requires many nullable columns

Foreign Keys
P– Pros
• Reduce redundancy
• Better modeling of data
– Cons
• Slower than denormalized table
• Slightly more complicated to query against

Join Tables
Pros– Pros
• Built on foreign key model, enables many:many relationships
– Cons
• Slower yet and even more complex querying

Joins
– Pros
• Allows for any possible query a user can think of without having
to predefine the requirements in the schema design
C– Cons
• No model enforcement
– Can join ‘age’ and ‘office floor’ columns – but does it make sense?
• Can be complicated/confusing to write; results may not appear
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
lcolumns
– <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 duplicatesUnordered/ordered collection allowing duplicates
• Realized through Collection/List
• Requires value column
idb– <idbag>
• Used for many-to-many relationships
• Same as Bag but with additional identifierSame as Bag, but with additional identifier
column used for surrogate keys
• Requires an ID Generator just like Entity classes



03-hibernate-Association_and_Collection_Mapping
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 t th d i bj t i fil3. Create the domain object mapping files
– <domain_object>.hbm.xml
4 Make Hibernate aware of the mapping files4. Make Hibernate aware of the mapping files
– Update the hibernate.cfg.xml with list of mapping files
5 Implement a HibernateUtil class5. Implement a HibernateUtil class
– Usually taken from the Hibernate documentation
6. Write your code


02-hibernate-A_Simple_Example
http://courses.coreservlets.com/Course-Materials/hibernate.html




  • N-Tier Architecture


Application is made up of layers or tiers
– Each layer encapsulates specific responsibilities
– Enables changes in one area with minimal impact to other
areas of the applicationareas of the application

• Common tiers
– Presentation
• ‘View’ in model-view-controller
• Responsible for displaying data only.  No business logic
Service– Service
• Responsible for business logic
– Persistence
• Responsible for storing/retrieving data


01-hibernate-Introduction_to_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 are often encountered when a relational database management system (RDBMS) is being used by a program written in an object-oriented programming language or style; particularly when objects or class definitions are mapped in a straightforward way to database tables or relational schema.


Mismatches

Object-oriented concepts
Encapsulation
Object-oriented programs are designed with techniques that result in encapsulated objects whose representation is hidden. Mapping such private object representation to database tables makes such databases fragile according to OOP (object-oriented programming) philosophy, since there are significantly fewer constraints for design of encapsulated private representation of objects compared to a database's use of public data, which must be amenable to upgrade, inspection and queries

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 are not supported by relational database systems


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 very often subtly to vastly different between the models, causing problems in mapping.

For example, most SQL systems support string types with varying collations and constrained maximum lengths (open-ended text types tend to hinder performance), while most OO languages consider collation only as an argument to sort routines and strings are intrinsically sized to available memory. A more subtle, but related example is that SQL systems often ignore trailing white space in a string for the purposes of comparison, whereas OO string libraries do not. It is typically not possible to construct new data types as a matter of constraining the possible values of other primitive types in an OO language.



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 be composed of other objects—often to a high degree—or specialize from a more general definition. This may make the mapping to relational schemas less straightforward. This is because relational data tends to be represented in a named set of global, unnested relation variables

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 generally handle query and manipulation through custom-built or lower-level, case and physical access path specific imperative operations


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 some attempts at building object-oriented database management systems (OODBMS) that would avoid the impedance mismatch problem. They have been less successful in practice than relational databases however, partly due to the limitations of OO principles as a basis for a data model

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 XForms) and native XML databases on the server that use the XQuery language for data selection. This allows a single data model and a single data selection language (XPath) to be used in the client, in the rules engines and on the persistence serve



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 some of the problems we will face in the previous strategy.

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 object oriented “is a” relationship into a relational “has a” relationship using foreign keys.


http://simsonlive.wordpress.com/2008/03/09/how-inheritance-works-in-hibernate/




  • 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(Single Table Strategy)
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 TwoWheelerVehicle and FourWheelerVehicle are inherited from Vehicle Abstract class


1. Table per concrete class with unions
In this case there will be 2 tables
Tables: TwoWheelerVehicle, FourWheelerVehicle[all common attributes will be duplicated]

2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database called 'Vehicle' that will represent all the attributes required for all 3 classes.
But it needs some discriminating column to differentiate between TwoWheelerVehicle and  FourWheelerVehicle;


3. Table per subclass
In this case there will be 3 tables represent TwoWheelerVehicle , FourWheelerVehicle and Vehicle



There are three possible strategies to use.
    Single Table Strategy,
    With Table Per Class Strategy,
    With Joined Strategy




http://www.dineshonjava.com/p/implementing-inheritance-in-hibernate.html#.UfoIF11jG70





  • 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 UtilityVan.

1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.

2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan

3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan


http://www.interviewjava.com/2007/10/explain-different-inheritance-mapping.html



  • Hibernate Object Lifecycle


hibernate considers objects it can
tl bi ffmanage to always be in one of four
states
Transient– Transient
– Persistent
– Removed
– Detached


Transient State
All objects start off in the transient
ttstate
– Account account = new Account();
• account is a transient object
Hibernate is not aware of the object
instance


Persistent State
Hibernate is aware of, and managing, the object
This is the only state where objects are saved to the
database


Persistent State
Session session =
SessionFactory getCurrentSession();SessionFactory.getCurrentSession();
// ‘transient’ state – Hibernate is NOT aware that it exists
Account account = new Account();Account account  new Account();
// transition to the ‘persistent’ state. Hibernate is NOW
// aware of the object and will save it to the databasej
session.saveOrUpdate(account);
// modification of the object will automatically bejy
// saved because the object is in the ‘persistent’ state
account.setBalance(500);
// it th t ti// commit the transaction
session.getTransaction().commit();


Removed State
A previously persistent object that is
deleted from the database
– session.delete(account);



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



  • 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

1 comment: