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


Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

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

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