SlideShare a Scribd company logo
The   1st   Java   professional open source Convention – Israel 2006 Welcome
Persisting Your Objects in the Database World Baruch Sadogursky AlphaCSP
Agenda O/R mapping Problem definition Past, current and future solutions overview Getting started with Hibernate Concepts Architecture Answering O/R mapping problems Step by step demo Hibernate “Hot Stuff”
O/R Mapping The problem, the solutions
Software Infrastructure Components
The Object-Relational Impedance Mismatch Portability Inheritance mapping Associations mapping Object graph navigation
Infrastructure Development Bottleneck Application Development Infrastructure Development 20% 80% Work Harder Work Smarter Application Development Infrastructure Development 80% 20%
Object / Relational Mapping O/R Mapping: Determining how to persist objects and their relationships to permanent data storage Persistence layer of choice today – relational database Robust Mature Industry standard de-facto
Solutions – Entity EJBs (1.x – 2.x) Part of  J2EE EJB (1.x – 2.x) spec. Intrusive persistence Can’t be used outside of EJB container Difficult to port Complicated programming model Performance issues No support for inheritance Irrelevant technology
Solutions – TopLink Oracle product  Implements EJB 3.0 Excellent solution Closed-source Pricy
Solutions –JDO Part of  J2EE spec. Implementations mainly use bytecode injection Both closed-source and open-source implementations Mapping not standardized
Solutions – Hibernate
Solutions – Hibernate Natural programming model Support for ultra-fine-grained object models No build-time bytecode enhancement Extreme scalability Detached objects support Transitive persistence
Solutions – Hibernate Integration Support Part of  JBoss JEMS De-facto standard The query language Support for "application" transactions  Free / open source
Solutions –EJB 3.0 The persistence API and query language in  JSR-220  inspired by Hibernate De-jure standard Gavin King, the author of Hibernate is active in the expert group “The Next Generation of EJB Development” lecture by Frederic Simon covers EJB 3 in deep
Getting Started With Hibernate
Persistence Architecture From “Hibernate in Action”
Persistence Life Cycle From “Hibernate in Action”
Persistence Engine Non intrusive persistence
Initialization Of Persistence Engine Loading configuration Specifying persistent classes and locating mapping files Building  SessionFactory  connected to the specified database Obtaining database session Starting transaction on the session (optional)
Database Manipulations Object-to-database and vice-versa manipulations are done with the Session methods Queries are submitted in Hibernate Query Language (HQL) SQL-like syntax Object orientation
HQL Example Same results in: SQL: SELECT  cust.name, cust.address, cust.phone, cust.id, cust.current_order  FROM  customers cust, stores store, locations loc, store_customers sc,product prod  WHERE  prod.name =  'widget‘   AND  store.loc_id = loc.id  AND  loc.name  IN  ( 'Melbourne' ,  'Sydney' )  AND  sc.store_id = store.id  AND  sc.cust_id = cust.id  AND  prod.id =  ALL ( SELECT  item.prod_id  FROM  line_items item, orders o  WHERE  item.order_id = o.id  AND  cust.current_order = o.id); HQL: select  cust  from  Product prod, Store store  inner join  store.customers cust  where  prod.name =  'widget'      and  store.location.name  in  ( 'Melbourne' ,  'Sydney' )      and  prod =  all elements (cust.currentOrder.lineItems);
Criteria-Database Manipulations Queries have drawbacks Unusual solution – Criteria API Java objects as filters Some limitations apply Criteria by Example
Demo Class Diagram
Demo O/R mapping 1  < hibernate-mapping >  2  < class   name= “…CompactDisk&quot;   table= &quot;CD&quot; >  3  < id   name= &quot;id&quot;   column= &quot;CD_ID“ …> 4  < generator   class= &quot;native&quot; />  5  </ id >  6  < property   name= &quot;title&quot;   column= &quot;CD_TITLE&quot; />  7  < property   name= &quot;author&quot;   column= &quot;CD_AUTHOR&quot; />  8  < property   name= &quot;publicationDate&quot;   column= &quot;CD_PUBLICATION_DATE&quot; />  9  < property   name= &quot;category&quot;   column= &quot;CD_CATEGORY&quot; />  10  < property   name= &quot;price&quot;   column= &quot;CD_PRICE&quot; />  11  < property   name= &quot;count&quot;   column= &quot;CD_COUNT&quot; />  12  < bag   name= &quot;tracks“  …>  13  < key   column= &quot;TRACK_ID&quot; />  14  < one-to-many   class= “…Track&quot; />  15  </ bag >  16  </ class >  17  </ hibernate-mapping > 1  < hibernate-mapping >  2  < class   name= “…Track&quot;   table= &quot;TRACK&quot; >  3  < id   name= &quot;id&quot;   column= &quot;TRACK_ID&quot;  …>  4  < generator   class= &quot;native&quot; />  5  </ id >  6  < property   name= &quot;name&quot;   column= &quot;TRACK_NAME&quot; />  7  < property   name= &quot;duration&quot;   column= &quot;TRACK_DURATION&quot; /> 8   < many-to-one   name= &quot;cd&quot;   column= &quot;CD_ID&quot;   class= “…CompactDisk&quot;   not-null= &quot;true&quot; />  9   </ class >  10   </ hibernate-mapping >
Rules For Class Definition Best to have JavaBeans-style accessors and mutators ( getXxx()  and  setXxxx() ) Must have default non-argument constructor Not final Identifier field recommendations: Primitive type Primitive wrapper String Date User-defined class (only recommended for composite identifiers in legacy DBs)
Creating Mapping File Object to Relational table (O-R) mapping defined in XML mapping file To prevent “metadata hell“: One file per class Store it with the class Naming convention: classname.hbm.xml  (compactDisk.hbm.xml, track.hbm.xml)  Most important elements: <class> <id> <generator> <property> Relationship definitions
<class> Element Most Common Attributes No Custom persister class name persister No Flag, when “true“ only changed properties updated, and not the whole class dynamic-update No Flag, when “true“ only new properties inserted, and not the whole class dynamic-insert No Database schema to use Default – none schema No Table name to store the state in Default – same as class name table No Exact type of object in inheritance mapping (rarely used) discriminator-value No Custom proxy class name (rarely used for lazy fetching) proxy Yes Fully qualified name of the class to persist May be an interface name Req Description Attribute
<id> Element Most Common Attributes Nested element – <generator> determines how the PK should be generated  No Hibernate type Default – determined by reflection  type No Column name of the primary key Default – same as id property name column No The maximum length of the pk length No Signals that object is new and should be inserted. Options: null (default), any (always insert), none (always update), some valid value unsaved-value Yes The id property name (used in Java class - private field, or accessor/mutator pair) name Req Description Attribute
PK Generator Options This generator uses a 128-bit UUID. Generates String unique within network (IP and timestamp combination) uuid.hex DB sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi, Firebird, and InterBase sequence DB identity columns in DB2, MySQL, MS SQL Server, Sybase, HSQLDB, Informix, and HypersonicSQL identity Reads the maximum primary key column value of the table on startup and increments the value by one each time a new row is inserted. Only for exclusive access to the DB increment High/low algorithm.   Identifiers are unique only for a particular database. hilo Picks other identity generators depending on the db capabilities native Description Class
<property> Element Most Common Attributes No Flag, when “false“ only existent properties updated, exception otherwise insert No Allow/disallow same values Default – false unique No Flag, when “false“ only new properties inserted, exception otherwise update No Hibernate type Default – determined by reflection  type No Column name to store the property in Default – same as property name column No Allow/disallow null values Default – false not-null No The maximum length of the value length Yes The Java property name (private field, or accessor/mutator pair) name Req Description Attribute
Property Types Java primitives and wrappers string date, time, timestamp calendar, calendar_date big_decimal locale, timezone, currency class binary (byte array) serializable clob, blob
Relationship   Types One-to-one (composition) One-to-many   (aggregation) Many-to-many
Relationships Representation In Java classes: Reference type fields java.util.List, java.util.Set  or  java.util.Map  (not concrete classes) In relational tables: foreign keys  In mapping files: <one-to-one> or <many-to-one> elements Class fields represented by “name” attribute Foreign keys represented by “column” attribute <list>, <set> or <map> elements Class fields represented by “name” attribute Foreign keys represented by <key-column> sub-element
Hibernate Demo
Hibernate “Hot Stuff”
Hibernate Annotations In Hibernate 2 mappings can be declared in: XML .hbm.xml files XDoclet Hibernate 3 introduces additional way of mapping by metadata in  Java 5 annotations Tools support Build-time validation Part of EJB 3 spec. ( JSR 220 ) “ The Next Generation of EJB Development” lecture by Frederic Simon covers EJB 3 Annotations in deep
Annotations Example 1  @Entity  2  public   class  AnnoTrack {  3  4    @Id  5    private  Long  id;  6    private  String  name;  7    private   long   duration;  8    @ManyToOne  9    private  CompactDisk  cd;  10  private  Calendar  calendar;  11  @Transient  12  private  Integer  internalSerial;  13  // Getter/setter and business methods  14  }
User-Defined Types Mapping other properties to single column Boolean.TRUE  to  1 Mapping composite types to more than one column Person  to  PERSON.FIRST_NAME  and  PERSON.LAST_NAME
Automatic Dirty Checking Changes in persistent object are monitored by Hibernate Manipulate the objects by regular Java means All the changes will be persisted during flush Session caches all the objects, associated with it to perform the check
For multi-tier applications, running in different VMs Same objects are sent to the web tier, changed there and then sent back to the backend tier  Hibernate knows which part of subgraph to update Hibernate distinguishes between reattached and newly added objects Detached Object Support
Working with Detached Objects 1  public  List getItems()  throws  … {  2  Query query =  getSession().createQuery ( &quot;from  CompactDisk&quot; );  3  return  query.list();  4  } 1  cd.setCategory( &quot;Rock&quot; ); Retrieve objects in the backend: Manipulate objects in the webapp:
Working with Detached Objects 1  public   void  updateItem(CompactDisk cd)  throws  … {  2  getSession().update(cd);  3  }  Save changes in the backend:
Bidirectional transitioning from and to the mapping file ReverseEngTool – useful when legacy DB is present SchemaExport – useful for automated creation of a fresh DB Roundtrip Tools
Second Level Cache
Second Level Cache  Session – transaction-level cache Second-level cache levels: JVM Cluster Clustered Pluggable architecture “ Taking Control over Clustering Caching and Data Distribution” lecture by Eran Haggiag and Avishay Halperen covers JBoss TreeCache in deep
Second Level Cache Types clustered  (ip multicast), transactional JBoss TreeCache Clustered  (ip multicast) SwarmCache memory, disk OSCache memory, disk EHCache memory Hashtable  Type Cache
Lazy Initialization – The Problem Objects may refer to huge collections of other objects If Category was object, refer to all CDs of that Category Transitive persistence should bring them all from the database even if they aren’t needed
Lazy Initialization – The Solution By default a collection is fetched only when the application invokes an operation upon that collection Filters can be used to initialize the collection partially or to get its size Beware! Hibernate does not support lazy initialization for detached objects
Statistics & JMX management Hibernate can expose metrics of  SessionFactory  in 2 ways: Statistics  object, retrieved from  SessionFactory StatisticsService   JMX MBean Metrics: Related to the general  Session  usage Related to the entities, collections, queries, and caches as a whole (aka global metrics) Detailed, related to a particular entity, collection, query or cache region
Lifecycle Callbacks Actual operations (load, save, update) are performed by default implementation of lifecycle listeners You can extend the default implementation to add additional behavior
XML Data Binding Another way to represent data – XML trees Hibernate let you map DOM objects instead of POJOs in addition to POJOs
Stored procedures & hand-written SQL It is possible to specify handwritten SQL (including stored procedures) Utilize database specific features  Provides migration path from a direct SQL/JDBC based application to Hibernate  Can be created programmatically or declaratively
Documentation of generated SQL Hibernate can generate SQL statements with embedded comments Makes it easy to discover the source of a misbehaving query
References http://www.alphacsp.com Hibernate official site Reference Documentation ”Hibernate in Action” book by Christian Bauer and Gavin King ”Pro Hibernate 3” book “Hibernate: A Developer's Notebook” book
Your Turn Now Q & A
The   1st   Java   professional open source Convention – Israel 2006 Thank you !

More Related Content

PPTX
From I/O To RAM
PPT
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
PPTX
TheEdge10 : Big Data is Here - Hadoop to the Rescue
PDF
REST and JAX-RS
PPTX
Smart Data Conference: DL4J and DataVec
PDF
Apache Spark Fundamentals Meetup Talk
PDF
Ray and Its Growing Ecosystem
PDF
Apache Spark: The Analytics Operating System
From I/O To RAM
Breaking The Clustering Limits @ AlphaCSP JavaEdge 2007
TheEdge10 : Big Data is Here - Hadoop to the Rescue
REST and JAX-RS
Smart Data Conference: DL4J and DataVec
Apache Spark Fundamentals Meetup Talk
Ray and Its Growing Ecosystem
Apache Spark: The Analytics Operating System

What's hot (20)

PDF
Spark as the Gateway Drug to Typed Functional Programming: Spark Summit East ...
PDF
Deep Dive: Memory Management in Apache Spark
PDF
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
ODP
Internals
PDF
Spark 101
PPTX
Deep Learning: DL4J and DataVec
PDF
How Machine Learning and AI Can Support the Fight Against COVID-19
ODP
Quick introduction to Java Garbage Collector (JVM GC)
PDF
Elasticsearch And Apache Lucene For Apache Spark And MLlib
PDF
Writing Continuous Applications with Structured Streaming Python APIs in Apac...
PPTX
Introduction to Spark ML
PDF
Big learning 1.2
PDF
Building a Database for the End of the World
PDF
BDM25 - Spark runtime internal
PPT
Introduction to Hibernate
PDF
Convolutional Neural Networks at scale in Spark MLlib
PPTX
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
PDF
Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...
PDF
What's new with Apache Tika?
ODP
Apache Spark Internals
Spark as the Gateway Drug to Typed Functional Programming: Spark Summit East ...
Deep Dive: Memory Management in Apache Spark
Packed Objects: Fast Talking Java Meets Native Code - Steve Poole (IBM)
Internals
Spark 101
Deep Learning: DL4J and DataVec
How Machine Learning and AI Can Support the Fight Against COVID-19
Quick introduction to Java Garbage Collector (JVM GC)
Elasticsearch And Apache Lucene For Apache Spark And MLlib
Writing Continuous Applications with Structured Streaming Python APIs in Apac...
Introduction to Spark ML
Big learning 1.2
Building a Database for the End of the World
BDM25 - Spark runtime internal
Introduction to Hibernate
Convolutional Neural Networks at scale in Spark MLlib
Josh Patterson, Advisor, Skymind – Deep learning for Industry at MLconf ATL 2016
Text Classification in Python – using Pandas, scikit-learn, IPython Notebook ...
What's new with Apache Tika?
Apache Spark Internals
Ad

Similar to Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Convention 2006 (20)

PDF
NHibernate (The ORM For .NET Platform)
PPT
PPT
Slice: OpenJPA for Distributed Persistence
PDF
Nhibernatethe Orm For Net Platform 1226744632929962 8
PPT
PPT
Patni Hibernate
PPT
Apache Persistence Layers
PPT
Eclipse Day India 2011 - Extending JDT
PPT
Java Intro
PPT
Basic Hibernate Final
PPT
Introducing Struts 2
PDF
Spring data requery
PPT
PPT
Entity Persistence with JPA
PDF
Struts Tags Speakernoted
ODP
JavaEE Spring Seam
ODP
Practical catalyst
ODP
2008.07.17 발표
PPT
Boston Computing Review - Java Server Pages
PPT
I Feel Pretty
NHibernate (The ORM For .NET Platform)
Slice: OpenJPA for Distributed Persistence
Nhibernatethe Orm For Net Platform 1226744632929962 8
Patni Hibernate
Apache Persistence Layers
Eclipse Day India 2011 - Extending JDT
Java Intro
Basic Hibernate Final
Introducing Struts 2
Spring data requery
Entity Persistence with JPA
Struts Tags Speakernoted
JavaEE Spring Seam
Practical catalyst
2008.07.17 발표
Boston Computing Review - Java Server Pages
I Feel Pretty
Ad

More from Baruch Sadogursky (20)

PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
PDF
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
PDF
Data driven devops as presented at QCon London 2018
PDF
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
PDF
Java Puzzlers NG S03 a DevNexus 2018
PDF
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
PDF
Data driven devops as presented at Codemash 2018
PDF
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
PPTX
Best Practices for Managing Docker Versions as presented at JavaOne 2017
PDF
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
PPTX
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
PDF
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsbu...
PDF
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
PDF
Let’s Wing It: A Study in DevRel Strategy
PDF
Log Driven First Class Customer Support at Scale
PPTX
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
PDF
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...
DevOps Patterns & Antipatterns for Continuous Software Updates @ NADOG April ...
DevOps Patterns & Antipatterns for Continuous Software Updates @ DevOps.com A...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Oracle Code NY...
Data driven devops as presented at QCon London 2018
A Research Study Into DevOps Bottlenecks as presented at Oracle Code LA 2018
Java Puzzlers NG S03 a DevNexus 2018
Where the Helm are your binaries? as presented at Canada Kubernetes Meetups
Data driven devops as presented at Codemash 2018
A Research Study into DevOps Bottlenecks as presented at Codemash 2018
Best Practices for Managing Docker Versions as presented at JavaOne 2017
Troubleshooting & Debugging Production Microservices in Kubernetes as present...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at Devoxx 2017
Amazon Alexa Skills vs Google Home Actions, the Big Java VUI Faceoff as prese...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at DevOps Days Be...
Java Puzzlers NG S02: Down the Rabbit Hole as it was presented at The Pittsbu...
DevOps @Scale (Greek Tragedy in 3 Acts) as it was presented at The Pittsburgh...
Let’s Wing It: A Study in DevRel Strategy
Log Driven First Class Customer Support at Scale
[Webinar] The Frog And The Butler: CI Pipelines For Modern DevOps
Patterns and antipatterns in Docker image lifecycle as was presented at DC Do...

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Approach and Philosophy of On baking technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPT
Teaching material agriculture food technology
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Empathic Computing: Creating Shared Understanding
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25 Week I
Approach and Philosophy of On baking technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
Big Data Technologies - Introduction.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Mobile App Security Testing_ A Comprehensive Guide.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Diabetes mellitus diagnosis method based random forest with bat algorithm
Per capita expenditure prediction using model stacking based on satellite ima...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Teaching material agriculture food technology
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Convention 2006

  • 1. The 1st Java professional open source Convention – Israel 2006 Welcome
  • 2. Persisting Your Objects in the Database World Baruch Sadogursky AlphaCSP
  • 3. Agenda O/R mapping Problem definition Past, current and future solutions overview Getting started with Hibernate Concepts Architecture Answering O/R mapping problems Step by step demo Hibernate “Hot Stuff”
  • 4. O/R Mapping The problem, the solutions
  • 6. The Object-Relational Impedance Mismatch Portability Inheritance mapping Associations mapping Object graph navigation
  • 7. Infrastructure Development Bottleneck Application Development Infrastructure Development 20% 80% Work Harder Work Smarter Application Development Infrastructure Development 80% 20%
  • 8. Object / Relational Mapping O/R Mapping: Determining how to persist objects and their relationships to permanent data storage Persistence layer of choice today – relational database Robust Mature Industry standard de-facto
  • 9. Solutions – Entity EJBs (1.x – 2.x) Part of J2EE EJB (1.x – 2.x) spec. Intrusive persistence Can’t be used outside of EJB container Difficult to port Complicated programming model Performance issues No support for inheritance Irrelevant technology
  • 10. Solutions – TopLink Oracle product Implements EJB 3.0 Excellent solution Closed-source Pricy
  • 11. Solutions –JDO Part of J2EE spec. Implementations mainly use bytecode injection Both closed-source and open-source implementations Mapping not standardized
  • 13. Solutions – Hibernate Natural programming model Support for ultra-fine-grained object models No build-time bytecode enhancement Extreme scalability Detached objects support Transitive persistence
  • 14. Solutions – Hibernate Integration Support Part of JBoss JEMS De-facto standard The query language Support for &quot;application&quot; transactions Free / open source
  • 15. Solutions –EJB 3.0 The persistence API and query language in JSR-220 inspired by Hibernate De-jure standard Gavin King, the author of Hibernate is active in the expert group “The Next Generation of EJB Development” lecture by Frederic Simon covers EJB 3 in deep
  • 16. Getting Started With Hibernate
  • 17. Persistence Architecture From “Hibernate in Action”
  • 18. Persistence Life Cycle From “Hibernate in Action”
  • 19. Persistence Engine Non intrusive persistence
  • 20. Initialization Of Persistence Engine Loading configuration Specifying persistent classes and locating mapping files Building SessionFactory connected to the specified database Obtaining database session Starting transaction on the session (optional)
  • 21. Database Manipulations Object-to-database and vice-versa manipulations are done with the Session methods Queries are submitted in Hibernate Query Language (HQL) SQL-like syntax Object orientation
  • 22. HQL Example Same results in: SQL: SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order FROM customers cust, stores store, locations loc, store_customers sc,product prod WHERE prod.name = 'widget‘ AND store.loc_id = loc.id AND loc.name IN ( 'Melbourne' , 'Sydney' ) AND sc.store_id = store.id AND sc.cust_id = cust.id AND prod.id = ALL ( SELECT item.prod_id FROM line_items item, orders o WHERE item.order_id = o.id AND cust.current_order = o.id); HQL: select cust from Product prod, Store store inner join store.customers cust where prod.name = 'widget'     and store.location.name in ( 'Melbourne' , 'Sydney' )     and prod = all elements (cust.currentOrder.lineItems);
  • 23. Criteria-Database Manipulations Queries have drawbacks Unusual solution – Criteria API Java objects as filters Some limitations apply Criteria by Example
  • 25. Demo O/R mapping 1 < hibernate-mapping > 2 < class name= “…CompactDisk&quot; table= &quot;CD&quot; > 3 < id name= &quot;id&quot; column= &quot;CD_ID“ …> 4 < generator class= &quot;native&quot; /> 5 </ id > 6 < property name= &quot;title&quot; column= &quot;CD_TITLE&quot; /> 7 < property name= &quot;author&quot; column= &quot;CD_AUTHOR&quot; /> 8 < property name= &quot;publicationDate&quot; column= &quot;CD_PUBLICATION_DATE&quot; /> 9 < property name= &quot;category&quot; column= &quot;CD_CATEGORY&quot; /> 10 < property name= &quot;price&quot; column= &quot;CD_PRICE&quot; /> 11 < property name= &quot;count&quot; column= &quot;CD_COUNT&quot; /> 12 < bag name= &quot;tracks“ …> 13 < key column= &quot;TRACK_ID&quot; /> 14 < one-to-many class= “…Track&quot; /> 15 </ bag > 16 </ class > 17 </ hibernate-mapping > 1 < hibernate-mapping > 2 < class name= “…Track&quot; table= &quot;TRACK&quot; > 3 < id name= &quot;id&quot; column= &quot;TRACK_ID&quot; …> 4 < generator class= &quot;native&quot; /> 5 </ id > 6 < property name= &quot;name&quot; column= &quot;TRACK_NAME&quot; /> 7 < property name= &quot;duration&quot; column= &quot;TRACK_DURATION&quot; /> 8 < many-to-one name= &quot;cd&quot; column= &quot;CD_ID&quot; class= “…CompactDisk&quot; not-null= &quot;true&quot; /> 9 </ class > 10 </ hibernate-mapping >
  • 26. Rules For Class Definition Best to have JavaBeans-style accessors and mutators ( getXxx() and setXxxx() ) Must have default non-argument constructor Not final Identifier field recommendations: Primitive type Primitive wrapper String Date User-defined class (only recommended for composite identifiers in legacy DBs)
  • 27. Creating Mapping File Object to Relational table (O-R) mapping defined in XML mapping file To prevent “metadata hell“: One file per class Store it with the class Naming convention: classname.hbm.xml (compactDisk.hbm.xml, track.hbm.xml) Most important elements: <class> <id> <generator> <property> Relationship definitions
  • 28. <class> Element Most Common Attributes No Custom persister class name persister No Flag, when “true“ only changed properties updated, and not the whole class dynamic-update No Flag, when “true“ only new properties inserted, and not the whole class dynamic-insert No Database schema to use Default – none schema No Table name to store the state in Default – same as class name table No Exact type of object in inheritance mapping (rarely used) discriminator-value No Custom proxy class name (rarely used for lazy fetching) proxy Yes Fully qualified name of the class to persist May be an interface name Req Description Attribute
  • 29. <id> Element Most Common Attributes Nested element – <generator> determines how the PK should be generated No Hibernate type Default – determined by reflection type No Column name of the primary key Default – same as id property name column No The maximum length of the pk length No Signals that object is new and should be inserted. Options: null (default), any (always insert), none (always update), some valid value unsaved-value Yes The id property name (used in Java class - private field, or accessor/mutator pair) name Req Description Attribute
  • 30. PK Generator Options This generator uses a 128-bit UUID. Generates String unique within network (IP and timestamp combination) uuid.hex DB sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi, Firebird, and InterBase sequence DB identity columns in DB2, MySQL, MS SQL Server, Sybase, HSQLDB, Informix, and HypersonicSQL identity Reads the maximum primary key column value of the table on startup and increments the value by one each time a new row is inserted. Only for exclusive access to the DB increment High/low algorithm. Identifiers are unique only for a particular database. hilo Picks other identity generators depending on the db capabilities native Description Class
  • 31. <property> Element Most Common Attributes No Flag, when “false“ only existent properties updated, exception otherwise insert No Allow/disallow same values Default – false unique No Flag, when “false“ only new properties inserted, exception otherwise update No Hibernate type Default – determined by reflection type No Column name to store the property in Default – same as property name column No Allow/disallow null values Default – false not-null No The maximum length of the value length Yes The Java property name (private field, or accessor/mutator pair) name Req Description Attribute
  • 32. Property Types Java primitives and wrappers string date, time, timestamp calendar, calendar_date big_decimal locale, timezone, currency class binary (byte array) serializable clob, blob
  • 33. Relationship Types One-to-one (composition) One-to-many (aggregation) Many-to-many
  • 34. Relationships Representation In Java classes: Reference type fields java.util.List, java.util.Set or java.util.Map (not concrete classes) In relational tables: foreign keys In mapping files: <one-to-one> or <many-to-one> elements Class fields represented by “name” attribute Foreign keys represented by “column” attribute <list>, <set> or <map> elements Class fields represented by “name” attribute Foreign keys represented by <key-column> sub-element
  • 37. Hibernate Annotations In Hibernate 2 mappings can be declared in: XML .hbm.xml files XDoclet Hibernate 3 introduces additional way of mapping by metadata in Java 5 annotations Tools support Build-time validation Part of EJB 3 spec. ( JSR 220 ) “ The Next Generation of EJB Development” lecture by Frederic Simon covers EJB 3 Annotations in deep
  • 38. Annotations Example 1 @Entity 2 public class AnnoTrack { 3 4 @Id 5 private Long id; 6 private String name; 7 private long duration; 8 @ManyToOne 9 private CompactDisk cd; 10 private Calendar calendar; 11 @Transient 12 private Integer internalSerial; 13 // Getter/setter and business methods 14 }
  • 39. User-Defined Types Mapping other properties to single column Boolean.TRUE to 1 Mapping composite types to more than one column Person to PERSON.FIRST_NAME and PERSON.LAST_NAME
  • 40. Automatic Dirty Checking Changes in persistent object are monitored by Hibernate Manipulate the objects by regular Java means All the changes will be persisted during flush Session caches all the objects, associated with it to perform the check
  • 41. For multi-tier applications, running in different VMs Same objects are sent to the web tier, changed there and then sent back to the backend tier Hibernate knows which part of subgraph to update Hibernate distinguishes between reattached and newly added objects Detached Object Support
  • 42. Working with Detached Objects 1 public List getItems() throws … { 2 Query query = getSession().createQuery ( &quot;from CompactDisk&quot; ); 3 return query.list(); 4 } 1 cd.setCategory( &quot;Rock&quot; ); Retrieve objects in the backend: Manipulate objects in the webapp:
  • 43. Working with Detached Objects 1 public void updateItem(CompactDisk cd) throws … { 2 getSession().update(cd); 3 } Save changes in the backend:
  • 44. Bidirectional transitioning from and to the mapping file ReverseEngTool – useful when legacy DB is present SchemaExport – useful for automated creation of a fresh DB Roundtrip Tools
  • 46. Second Level Cache Session – transaction-level cache Second-level cache levels: JVM Cluster Clustered Pluggable architecture “ Taking Control over Clustering Caching and Data Distribution” lecture by Eran Haggiag and Avishay Halperen covers JBoss TreeCache in deep
  • 47. Second Level Cache Types clustered (ip multicast), transactional JBoss TreeCache Clustered (ip multicast) SwarmCache memory, disk OSCache memory, disk EHCache memory Hashtable Type Cache
  • 48. Lazy Initialization – The Problem Objects may refer to huge collections of other objects If Category was object, refer to all CDs of that Category Transitive persistence should bring them all from the database even if they aren’t needed
  • 49. Lazy Initialization – The Solution By default a collection is fetched only when the application invokes an operation upon that collection Filters can be used to initialize the collection partially or to get its size Beware! Hibernate does not support lazy initialization for detached objects
  • 50. Statistics & JMX management Hibernate can expose metrics of SessionFactory in 2 ways: Statistics object, retrieved from SessionFactory StatisticsService JMX MBean Metrics: Related to the general Session usage Related to the entities, collections, queries, and caches as a whole (aka global metrics) Detailed, related to a particular entity, collection, query or cache region
  • 51. Lifecycle Callbacks Actual operations (load, save, update) are performed by default implementation of lifecycle listeners You can extend the default implementation to add additional behavior
  • 52. XML Data Binding Another way to represent data – XML trees Hibernate let you map DOM objects instead of POJOs in addition to POJOs
  • 53. Stored procedures & hand-written SQL It is possible to specify handwritten SQL (including stored procedures) Utilize database specific features Provides migration path from a direct SQL/JDBC based application to Hibernate Can be created programmatically or declaratively
  • 54. Documentation of generated SQL Hibernate can generate SQL statements with embedded comments Makes it easy to discover the source of a misbehaving query
  • 55. References http://www.alphacsp.com Hibernate official site Reference Documentation ”Hibernate in Action” book by Christian Bauer and Gavin King ”Pro Hibernate 3” book “Hibernate: A Developer's Notebook” book
  • 56. Your Turn Now Q & A
  • 57. The 1st Java professional open source Convention – Israel 2006 Thank you !