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

What's hot (20)

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

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

PDF
JPA and Hibernate
elliando dias
 
PPT
03 Object Relational Mapping
Ranjan Kumar
 
PPTX
Hibernate Training Session1
Asad Khan
 
PPT
Basic Hibernate Final
Rafael Coutinho
 
PPT
Patni Hibernate
patinijava
 
PPT
Hibernate
Murali Pachiyappan
 
PPTX
Hibernate
Prashant Kalkar
 
PDF
Hibernate 1x2
Meenakshi Chandrasekaran
 
PPTX
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
PDF
Hibernate in Action 1st Edition Christian Bauer
sanosaasi
 
PDF
ActiveJDBC - ActiveRecord implementation in Java
ipolevoy
 
PDF
Hibernate 3
Rajiv Gupta
 
PPT
Hibernate Tutorial
Ram132
 
PDF
Hibernate In Action 1st Edition Christian Bauer Gavin King
wydunkhi2731
 
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
PDF
S313431 JPA 2.0 Overview
Ludovic Champenois
 
PPTX
Hibernate tutorial
Mumbai Academisc
 
PPTX
Hibernate in XPages
Toby Samples
 
PDF
Persistence
Abdalla Mahmoud
 
PDF
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
JPA and Hibernate
elliando dias
 
03 Object Relational Mapping
Ranjan Kumar
 
Hibernate Training Session1
Asad Khan
 
Basic Hibernate Final
Rafael Coutinho
 
Patni Hibernate
patinijava
 
Hibernate
Prashant Kalkar
 
Module-3 for career and JFSD ppt for study.pptx
ViratKohli78
 
Hibernate in Action 1st Edition Christian Bauer
sanosaasi
 
ActiveJDBC - ActiveRecord implementation in Java
ipolevoy
 
Hibernate 3
Rajiv Gupta
 
Hibernate Tutorial
Ram132
 
Hibernate In Action 1st Edition Christian Bauer Gavin King
wydunkhi2731
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Arun Gupta
 
S313431 JPA 2.0 Overview
Ludovic Champenois
 
Hibernate tutorial
Mumbai Academisc
 
Hibernate in XPages
Toby Samples
 
Persistence
Abdalla Mahmoud
 
inf5750---lecture-2.-c---hibernate-intro.pdf
bhqckkgwglxjcuctdf
 
Ad

More from Baruch Sadogursky (20)

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

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
July Patch Tuesday
Ivanti
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 

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 !