Upload
baruch-sadogursky
View
1.357
Download
1
Tags:
Embed Size (px)
DESCRIPTION
Citation preview
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
The 1st Java professional open source
Convention – Israel 2006
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Persisting Your Objects in the
Database World
Baruch SadogurskyAlphaCSP
Page 3Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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”
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
O/R Mapping
The problem, the solutions
Page 5Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Software Infrastructure Components
Transaction management
Security management
Availability ensuring
Saving and restoring objects
Page 6Copyright AlphaCSP, The 1st Java open source convention Israel 2006
The Object-Relational Impedance Mismatch
• Portability• Inheritance mapping• Associations mapping• Object graph navigation
Page 7Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Infrastructure Development Bottleneck
Application Development
Infrastructure Development
20%
80%
Work Harder
Work Smarter
Application Development
Infrastructure Development
80%
20%
Page 9Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 10Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Solutions – TopLink
• Oracle product • Implements EJB 3.0• Excellent solution• Closed-source• Pricy
Page 11Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Solutions –JDO
• Part of J2EE spec.• Implementations mainly use
bytecode injection• Both closed-source and open-
source implementations• Mapping not standardized
Page 12Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Solutions – Hibernate
Page 13Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Solutions – Hibernate
• Natural programming model• Support for ultra-fine-grained
object models• No build-time bytecode
enhancement• Extreme scalability• Detached objects support• Transitive persistence
Page 14Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Solutions – Hibernate
• Integration• Support• Part of JBoss JEMS• De-facto standard• The query language• Support for "application"
transactions • Free / open source
Page 15Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Getting Started With Hibernate
Page 17Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Persistence Architecture
• From “Hibernate in Action”
Page 18Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Persistence Life Cycle
• From “Hibernate in Action”
Page 19Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Persistence Engine
• Non intrusive persistence
Database
POJOs
Mapping data
Session(Persistence Engine)
Page 21Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 22Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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);
Page 23Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Criteria-Database Manipulations
• Queries have drawbacks• Unusual solution – Criteria API
– Java objects as filters
• Some limitations apply• Criteria by Example
Page 24Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Demo Class Diagram
-id : long+title : string+author : string+publicationDate : string+category : string+price : double+count : int+tracks : Track
CompactDisk
-id : long+name : string+duration : long+cd : CompactDisk
Track
+cd
1
+tracks
*
test.cd
PK CD_ID
CD_TITLE CD_AUTHOR CD_PUBLICATION_DATE CD_CATEGORY CD_PRICE CD_COUNT
test.track
PK TRACK_ID
TRACK_NAME TRACK_DURATIONFK1 CD_ID
Page 25Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Demo O/R mapping1 <hibernate-mapping>
2 <class name=“…CompactDisk" table="CD">
3 <id name="id" column="CD_ID“…>
4 <generator class="native"/>
5 </id>
6 <property name="title" column="CD_TITLE"/>
7 <property name="author" column="CD_AUTHOR"/>
8 <property name="publicationDate" column="CD_PUBLICATION_DATE"/>
9 <property name="category" column="CD_CATEGORY"/>
10 <property name="price" column="CD_PRICE"/>
11 <property name="count" column="CD_COUNT"/>
12 <bag name="tracks“ …>
13 <key column="TRACK_ID"/>
14 <one-to-many class=“…Track"/>
15 </bag>
16 </class>
17 </hibernate-mapping>
1 <hibernate-mapping>
2 <class name=“…Track" table="TRACK">
3 <id name="id" column="TRACK_ID" …>
4 <generator class="native"/>
5 </id>
6 <property name="name" column="TRACK_NAME"/>
7 <property name="duration" column="TRACK_DURATION"/>
8 <many-to-one name="cd" column="CD_ID" class=“…CompactDisk" not-null="true"/>
9 </class>
10 </hibernate-mapping>
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Hibernate Demo
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Hibernate “Hot Stuff”
Page 37Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 38Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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 }
Page 39Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 40Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 41Copyright AlphaCSP, The 1st Java open source convention Israel 2006
• 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
Page 44Copyright AlphaCSP, The 1st Java open source convention Israel 2006
• 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
Page 45Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Second Level Cache
2nd L
evel
Cac
he
Clu
ster
ed D
atab
ase
Database
Database
Database
Hib
erna
te C
ore
Session
Session
Session
Page 46Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 48Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 49Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 50Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 51Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 52Copyright AlphaCSP, The 1st Java open source convention Israel 2006
XML Data Binding
• Another way to represent data – XML trees• Hibernate let you map DOM objects
– instead of POJOs– in addition to POJOs
Page 53Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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
Page 54Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Documentation of generated SQL
• Hibernate can generate SQL statements with embedded comments
• Makes it easy to discover the source of a misbehaving query
Page 55Copyright AlphaCSP, The 1st Java open source convention Israel 2006
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 Notebo
ok” book
Page 56Copyright AlphaCSP, The 1st Java open source convention Israel 2006
Your Turn Now
Q & A
Copyright AlphaCSP, The 1st Java open source convention Israel 2006
The 1st Java professional open source
Convention – Israel 2006