Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Convention 2006
Upcoming SlideShare
Loading in...5
×
 

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

on

  • 1,344 views

 

Statistics

Views

Total Views
1,344
Views on SlideShare
1,343
Embed Views
1

Actions

Likes
0
Downloads
13
Comments
0

1 Embed 1

http://www.techgig.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

    • 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 !