Introduction to Hibernate Framework | Hibernate Framework in Java
Hibernate An Introduction
-
Upload
nguyen-cao -
Category
Technology
-
view
502 -
download
1
description
Transcript of Hibernate An Introduction
Basic Fundamentals Conclusion
Hibernate: An Introduction
Cao Duc [email protected]
Software DesignerHP Software Products and Solution
May 3, 2012
Basic Fundamentals Conclusion
Talk Outline
1 BasicGetting StartedProblemChallenges
2 FundamentalsConceptsData ModelPersistent LifecycleHQLArchitecture
3 Conclusion
Basic Fundamentals Conclusion
Getting Started
Setting up the Environment
JDKAnt/MavenMySQL/PostgreSQL/Oracle, etc.JDBCEclipse Hibernate Tools
Basic Fundamentals Conclusion
Getting Started
Hibernate ORM distribution
Basic Fundamentals Conclusion
Problem
Hibernate - Definitions
by Hibernate.orgHibernate is concerned with helping yourapplication to achieve persistence. . . Persistencesimply means that we would like our application’sdata to outlive the applications process. . . wouldlike the state of (some of) our objects to livebeyond the scope of the JVM so that the samestate is available later.
by Wikipedia.orgHibernate is an object-relational mapping (ORM)library for the Java language, . . . a framework formapping an object-oriented domain model to atraditional relational database . . .
Basic Fundamentals Conclusion
Problem
Traditional View
Basic Fundamentals Conclusion
Problem
Traditional View (cont.)
Basic Fundamentals Conclusion
Problem
Hibernate View
Basic Fundamentals Conclusion
Challenges
Two Different Worlds
Object-Oriented SystemsSystem composed of objects interacting with each otherObjects encapsulate data and behaviors
Relational DatabasesData is stored in tables composed of rows
Basic Fundamentals Conclusion
Challenges
Obstacles
IdentityGranularityAssociationsNavigationInheritance & PolymorphismData type mismatches
Basic Fundamentals Conclusion
Concepts
Plain Old Java Object (POJOs)
In general, a POJO is a Java object not bound by any restrictionother than those forced by the Java Language Specification.However, due to technical difficulties and other reasons, in thecontext of Hibernate, a POJO is defined as follow:
No-argument class constructorProperty accessor (get/set) methodsClass is not declared final nor has final methods.Collection-typed attributes must be declared as interfacetypes.
Basic Fundamentals Conclusion
Data Model
Example Application: EventApp
Event-management application used to manage a conferencewith speakers, attendees, and various locations, among otherthings.
Basic Fundamentals Conclusion
Data Model
An Example: EventApp
Basic Fundamentals Conclusion
Data Model
Identity Mapping
<id name="id" column="id" type="long"><generator class="native"/></id>
Mapped classes must declare the primary key column ofthe database table.Generators using the native class will use identity orsequence columns depending on available databasesupport. If neither method is supported, the nativegenerator falls back to a high/low generator method tocreate unique primary key values.The native generator returns a short, integer, or long value.Hibernate documentation about Identity mapping here.
Basic Fundamentals Conclusion
Data Model
Property Mapping
<property name="startDate" column="start_date"type="date"/>
A typical Hibernate Property mapping defines a POJOproperty name, a database column name, and the name ofa Hibernate type, and it is often possible to omit the type.Hibernate uses reflection to determine the Java type of theproperty.Details about Hibernate Types mapping here.Hibernate documentation about Property mapping here.
Basic Fundamentals Conclusion
Data Model
Entity Mapping
<class name="Event" table="events"><!-- define identity, properties, components,collections, associations here... --></class>
A typical Hibernate Entity mapping defines a POJO classname, a database table name.By default, all class names are automatically “imported”into the namespace of HQLHibernate documentation about Entity mapping here.
Basic Fundamentals Conclusion
Data Model
Component Mapping
<component name="componentName"class="componentClass">
<!-- defines properties of the component herethese properties will be mapped to columns ofthe enclosing entity--></class>
A Hibernate Component mapping is defined within anEntity mapping several objects into one single table of theenclosing entity.Hibernate documentation about Component mapping here.
Basic Fundamentals Conclusion
Data Model
Put it all together
Hibernate Mapping files:
The Event.hbm.xml mapping file
Basic Fundamentals Conclusion
Data Model
Put it all together (cont.)
The Location.hbm.xml mapping file
Basic Fundamentals Conclusion
Data Model
Put it all together (cont.)
Hibernate Configuration hibernate.cfg.xml file:
Basic Fundamentals Conclusion
Data Model
Collection Mapping
Common Collections: sets, lists, bags, maps of value types.Value Type:
An object of value type has no database identity; it belongsto an entity instance, and its persistent state is embeddedin the table row of the owning entityValue-typed classes do not have identifiers or identifierproperties
Basic Fundamentals Conclusion
Data Model
Collection Mapping (cont.)
Hibernate persistent collections
Basic Fundamentals Conclusion
Data Model
Collection Mapping (cont.)
Example of persisting collections
Basic Fundamentals Conclusion
Data Model
Inheritance Mapping
Table per concrete class with union:
Basic Fundamentals Conclusion
Data Model
Inheritance Mapping (cont.)
Table per class hierarchy:
Basic Fundamentals Conclusion
Data Model
Inheritance Mapping (cont.)
Table per subclass:
Basic Fundamentals Conclusion
Persistent Lifecycle
Object States
TransientThe object is not associated with any persistencecontext. It has no persistent identity (primary keyvalue).
PersistentThe object is currently associated with apersistence context. It has a persistent identity(primary key value) and, perhaps, a correspondingrow in the database. Hibernate guarantees thatpersistent identity is equivalent to Java identity.
Basic Fundamentals Conclusion
Persistent Lifecycle
Object States (cont.)
DetachedThe instance was once associated with apersistence context, but that context was closed,or the instance was serialized to another process.It has a persistent identity and, perhaps, acorrsponding row in the database. For detachedinstances, Hibernate makes no guarantees aboutthe relationship between persistent identity andJava identity
Basic Fundamentals Conclusion
Persistent Lifecycle
State Transition Diagram
Basic Fundamentals Conclusion
Persistent Lifecycle
Case 1: Making an object persistent
Item item = new Item();item.setName("Playstation3 incl. all accessories");item.setEndDate( ... );Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Serializable itemId = session.save(item);tx.commit();session.close();
Basic Fundamentals Conclusion
Persistent Lifecycle
Case 2: Retrieving a persistent object
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.load(Item.class,new Long(1234));// Item item = (Item) session.get(Item.class,// new Long(1234));tx.commit();session.close();
Basic Fundamentals Conclusion
Persistent Lifecycle
Case 3: Modifying a persistent object
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.get(Item.class,new Long(1234));item.setDescription("This Playstation isas good as new!");tx.commit();session.close();
Basic Fundamentals Conclusion
Persistent Lifecycle
Case 4: Making a persistent object transient
Session session = sessionFactory.openSession();Transaction tx = session.beginTransaction();Item item = (Item) session.load(Item.class,new Long(1234));session.delete(item);tx.commit();session.close();
Basic Fundamentals Conclusion
Persistent Lifecycle
Case 5: Reattaching a modified detached instance
// Loaded in previous Sessionitem.setDescription(...);Session sessionTwo = sessionFactory.openSession();Transaction tx = sessionTwo.beginTransaction();sessionTwo.update(item);item.setEndDate(...);tx.commit();sessionTwo.close();
Basic Fundamentals Conclusion
HQL
Query
HQL Query:
HQL SQLQuery:
Basic Fundamentals Conclusion
HQL
Parameter Binding
Basic Fundamentals Conclusion
HQL
Joins
Join:
Left Join:
Basic Fundamentals Conclusion
HQL
Criteria API
Some developers prefer to build queries dynamically, using anobject-oriented API, rather than building query strings.Hibernate provides an intuitive org.hibernate.Criteriarepresents a query against a particular persistent class:
Basic Fundamentals Conclusion
HQL
DetachedCriteria
A DetachedCriteria is used to express a subquery.
Basic Fundamentals Conclusion
Architecture
Structural Components
More in depth explanation can be found here.
Basic Fundamentals Conclusion
Architecture
Hibernate Flexibility and Extendibility
Extension points:Dialects (for different databases)Custom mapping typesID generatorsCache, CacheProviderTransaction, TransactionFactoryPropertyAccessorProxyFactoryConnectionProvider
Basic Fundamentals Conclusion
Why Hibernate?
Free, open source Java packageRelease developers from data persistent related tasks,help to focus on objects and features of applicationNo need for JDBC API for Result handlingDatabase almost-independenceEfficient queries
Basic Fundamentals Conclusion
THANK YOU *-*