17.7 Mapping Data to Objects by Using ORM Frameworks

Because of the need to easily move data back and forth from a database to a Java object, numerous vendors have developed frameworks for mapping objects to relational databases. This is a powerful capability since object-oriented programming and relational databases have always had an impedance mismatch: objects understand both state and behavior and can be traversed through relationships with other objects, whereas relational databases store information in tables but are typically related through primary keys.

Table 17.1 summarizes a few popular object-to-relational mapping (ORM) frameworks. Numerous other ORM frameworks are available. For a comparison of Java-based ORM products, see http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison. Another excellent source for ORM frameworks and tutorials is located at http://www.javaskyline.com/database.html. (Remember that the book's source code archive at http://www.coreservlets.com/ contains up-to-date links to all URLs mentioned in the book.)

Table 17.1. Object-to-Relational Mapping Frameworks

Framework

URL

Castor

http://castor.exolab.org/

CocoBase

http://www.cocobase.com/

FrontierSuite

http://www.objectfrontier.com/

Kodo JDO

http://www.solarmetric.com/

ObJectRelationalBridge

http://db.apache.org/ojb/

TopLink

http://otn.oracle.com/products/ias/toplink/

Many, but not all, of these frameworks support the API for Java Data Objects (JDO). The JDO API provides a complete object-oriented approach to manage objects that are mapped to a persistent store (database). Detailed coverage of ORM frameworks and JDO is beyond the scope of this book. However, we provide a brief summary to show the power that JDO provides. For more information on JDO, see the online material at http://java.sun.com/products/jdo/ and http://jdocentral.com/. In addition, you can refer to Core Java Data Objects by Sameer Tyagi et al.

In JDO frameworks, the developer must provide XML-based metadata for each Java class that maps to the relational database. The metadata defines the persistent fields in each class and the potential role of each field relative to the database (e.g., the primary key). Once the metadata and source code for each Java class are defined, the developer must run a framework utility to generate the necessary JDO code to support persistence of the object's fields in the persistent store (database).

JDO framework utilities take one of two approaches to modify a Java class in support of the persistent store: the first approach is to modify the source code before compiling, the second approach is to modify the bytecode ( .class file) after compiling the source code. The second approach is more common because it simplifies the maintenance of the source codethe generated database code is never seen by the developer.

In the case of a JDO implementation for an SQL database, the framework utility generates all the necessary code required by the JDO persistence manager to INSERT new rows in the database, as well as to perform UPDATE and DELETE operations for persisting modifications to the data. The developer is not required to write any SQL or JDBC code; the framework utility generates all the necessary code, and the persistence manager generates all the necessary communication with the database. Once the framework is set up, the developer simply needs to create objects and understand the JDO API.

Listing 17.15 shows Music.jdo , an example of how metadata for the Music class (Listing 17.16) is defined for SolarMetric's Kodo JDO implementation. The XML file Music.jdo maps the Music class to a table in the database by using an extension element with a key attribute of table and a value attribute of music . It is not necessary that the database already have a table named music ; in fact, the Kodo framework creates all tables necessary in the database for the persistent storage, possibly using modified table names . The name attribute simply defines a mapping for the framework.

The . jdo file further designates a field element for each field in the class that must be persisted in the database. Each field element defines an extension element to map a field in the class to a column in the database table, where the value attribute clarifies the name of the database column. The extension elements are vendor specific, so be sure to consult the documentation of your JDO vendor for the proper values for the key attribute.

The PersistenceManager class provides access to the persistent store (database). For example, Listing 17.17 shows how to insert fields associated with new objects into the persistent store with the makePersistentAll method. Changes to the persistent store are managed as a transaction and must be placed between calls to the begin and commit methods of the Transaction class. Thus, to insert the fields associated with a Music object into the database, you simply call the appropriate set Xxx methods on the Music object and then invoke the makePersistentAll method within a transaction. The JDO persistence manager automatically creates and executes the SQL statements to commit the data to the database. In a similar manner, the deletion of fields associated with a Music object is handled through the makeDeletePersistent method of PersistenceManager . For more complicated interaction with the persistent store, JDO provides a Query class to execute queries and return the results as a Collection of objects.

Lastly, the location of the database, the username, the password, and other system-specific information is read from system properties (specified by Listing 17.18 in this example).

Listing 17.15 Music.jdo
 <?xml version="1.0"?> <!DOCTYPE jdo PUBLIC "-//Sun Microsystems, Inc.//DTD Java Data Objects Metadata 1.0//EN" "http://java.sun.com/dtd/jdo_1_0.dtd"> <jdo>   <package name="coreservlets.jdo">     <class name="Music" >  <extension vendor-name="kodo"   key="table" value="music"/>  <extension vendor-name="kodo"                  key="lock-column" value="none"/>       <extension vendor-name="kodo"                  key="class-column" value="none"/>       <field name="id" primary-key="true">         <extension vendor-name="kodo"                    key="data-column" value="id"/>       </field>       <field name="composer">         <extension vendor-name="kodo"                    key="data-column" value="composer"/>       </field>       <field name="concerto">         <extension vendor-name="kodo"                    key="data-column" value="concerto"/>       </field>       <field name="available">         <extension vendor-name="kodo"                    key="data-column" value="available"/>       </field>       <field name="price">         <extension vendor-name="kodo"                    key="data-column" value="price"/>       </field>     </class>   </package> </jdo> 
Listing 17.16 Music.java
 package coreservlets.jdo;  /** Music object corresponding to a record in a database.   *  A Music object/record provides information about   *  a concerto that is available for purchase and   *  defines fields for the ID, composer, concerto,   *  items available, and sales price.   */ public class Music {   private int id;   private String composer;   private String concerto;   private int available;   private float price;   public Music() { }   public Music(int id, String composer, String concerto,                int available, float price) {     setId(id);     setComposer(composer);     setConcerto(concerto);     setAvailable(available);     setPrice(price);   }   public void setId(int id) {     this.id = id;   }   public int getId() {     return(id);   }   public void setComposer(String composer) {     this.composer = composer;   }   public String getComposer() {     return(concerto);   }   public void setConcerto(String concerto) {     this.concerto = concerto;   }   public String getConcerto() {     return(composer);   }   public void setAvailable(int available) {     this.available = available;   }   public int getAvailable() {     return(available);   }   public void setPrice(float price) {     this.price = price;   }   public float getPrice() {     return(price);   } } 
Listing 17.17 PopulateMusicTable.java
 package coreservlets.jdo; import java.util.*; import java.io.*; import javax.jdo.*; /** Populate database with music records by using JDO.  */ public class PopulateMusicTable {   public static void main(String[] args) {     // Create seven new music objects to place in the database.     Music[] objects = {       new Music(1, "Mozart", "No. 21 in C# minor", 7, 24.99F),       new Music(2, "Beethoven", "No. 3 in C minor", 28, 10.99F),       new Music(3, "Beethoven", "No. 5 Eb major", 33, 10.99F),       new Music(4, "Rachmaninov", "No. 2 in C minor", 9, 18.99F),       new Music(5, "Mozart", "No. 24 in C minor", 11, 21.99F),       new Music(6, "Beethoven", "No. 4 in G", 33, 12.99F),       new Music(7, "Liszt", "No. 1 in Eb major", 48, 10.99F)     };     // Load properties file with JDO information. The properties     // file contains ORM Framework information specific to the     // vendor and information for connecting to the database.     Properties properties = new Properties();     try {       FileInputStream fis =         new FileInputStream("jdo.properties");       properties.load(fis);     } catch(IOException ioe) {       System.err.println("Problem loading properties file: " +                          ioe);       return;     }     // Initialize manager for persistence framework.  PersistenceManagerFactory pmf =   JDOHelper.getPersistenceManagerFactory(properties);   PersistenceManager pm = pmf.getPersistenceManager();  // Write the new Music objects to the database.     Transaction transaction = pm.currentTransaction();  transaction.begin();   pm.makePersistentAll(objects);   transaction.commit();  pm.close ();   } } 
Listing 17.18 jdo.properties
 # Configuration information for Kodo JDO Framework and # MySQL database. javax.jdo.PersistenceManagerFactoryClass=   com.solarmetric.kodo.impl.jdbc.JDBCPersistenceManagerFactory javax.jdo.option.RetainValues=true javax.jdo.option.RestoreValues=true javax.jdo.option.Optimistic=true javax.jdo.option.NontransactionalWrite=false javax.jdo.option.NontransactionalRead=true javax.jdo.option.Multithreaded=true javax.jdo.option.MsWait=5000 javax.jdo.option.MinPool=1 javax.jdo.option.MaxPool=80 javax.jdo.option.IgnoreCache=false  javax.jdo.option.ConnectionUserName: brown   javax.jdo.option.ConnectionURL: jdbc:mysql://localhost/csajsp   javax.jdo.option.ConnectionPassword: larry   javax.jdo.option.ConnectionDriverName: com.mysql.jdbc.Driver  com.solarmetric.kodo.impl.jdbc.WarnOnPersistentTypeFailure=true com.solarmetric.kodo.impl.jdbc.SequenceFactoryClass=   com.solarmetric.kodo.impl.jdbc.schema.DBSequenceFactory com.solarmetric.kodo.impl.jdbc.FlatInheritanceMapping=true com.solarmetric.kodo.EnableQueryExtensions=false com.solarmetric.kodo.DefaultFetchThreshold=30 com.solarmetric.kodo.DefaultFetchBatchSize=10 com.solarmetric.kodo.LicenseKey=5A8A-D98C-DB5F-6070-6000 


Core Servlets and JavaServer Pages (Vol. 1.Core Technologies)
Core Servlets and Javaserver Pages: Core Technologies, Vol. 1 (2nd Edition)
ISBN: 0130092290
EAN: 2147483647
Year: 2002
Pages: 194

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net