Now that we've decided on our classes and how we want to define their identities we can decide on the precise persistence definition. In this section we'll describe how to persist these objects to a new database schema where we can create new tables and don't need to write to some existing table. Some JDO tools provide an IDE to generate Meta-Data files, but JPOX doesn't currently. Either way it is a good idea to become familiar with the structure of these files since they define how your classes are persisted. Lets start with the header area. You add a block like this to define that the file is JDO Meta-Data
<?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>
Now lets define the persistence for our Pack class. We are going to use datastore identity here, meaning that JPOX will assign id's to each Pack object persisted. We define it as follows
<package name="org.jpox.examples">
<class name="Pack" identity-type="datastore">
<field name="name" persistence-modifier="persistent">
<extension vendor-name="jpox" key="length" value="max 100"/>
</field>
<field name="description" persistence-modifier="persistent">
<extension vendor-name="jpox" key="length" value="max 255"/>
</field>
<field name="cards" persistence-modifier="persistent">
<collection element-type="org.jpox.examples.Card"/>
</field>
</class>
Here we've defined that our name field will be persisted to a VARCHAR(100) column, our description field will be persisted to a VARCHAR(255) column, and that our cards field is a Collection containing org.jpox.examples.Card objects. This final information is to inform JPOX to link the table for this class (via a foreign key) to the table for Card class. This is what is termed a Normal relationship. Please refer to the 1-N Relationships Guide for more details on this. We'll discuss Inverse relationships in a different example. Now lets define the persistence for our Card class. We are going to use application identity here, meaining that we define the id's for any object of type Card. We define it as follows
<class name="Card" identity-type="application"
objectid-class="org.jpox.examples.Card$CardKey">
<field name="suit" primary-key="true">
<extension vendor-name="jpox" key="length" value="max 10"/>
</field>
<field name="number" primary-key="true">
<extension vendor-name="jpox" key="length" value="max 20"/>
</field>
</class>
</package>
Here we've defined that our class uses application identity and that its primary key for this is org.jpox.examples.Card$CardKey (since its an inner class, we use the $ notation to define that). We've also defined that the 2 fields in this class are part of the primary key. You must define which fields are in the primary key. We finally terminate the Meta-Data file with the closing tag
</jdo>
|