2.4. Inventory Growth

Now that we have the basic pet store framework in place, let's add support for the next pet in our list: the rabbit. The rabbit is a bit different than the dog; pet stores sell them all for the same price, but gender is critically important since rabbits reproduce rather easily and quickly. Let's put together a class representing a rabbit.

In this chapter, you will see some more queries and write a two-sided many-to-many relation between objects.

Provided with this tutorial is a file called Rabbit.java which contains a sample Rabbit implementation. Let's get it compiled and loaded:

  1. Examine and compile Rabbit.java.

    javac Rabbit.java
  2. Add an entry for Rabbit to package.jdo.

    The Rabbit class above contains a two-sided many-to-many relationship, between parents and children. From the Java side of things, a two-sided many-to-many relationship is simply a pair of collections that are conceptually linked. There is no special Java work necessary to express a relationship. However, you must identify the relationship in the JDO metadata for the mapping tool to create the most efficient schema. The snippet below should be inserted into the package.jdo file. It identifies both the type of data in the collection (the element-type attribute) and the name of the other side of the relation. Notice the use of the extension element. Since the concept of a two-sided relationship is not a data store-independent concept, the JDO specification does not provide built-in support for identifying the inverse of a relation. With this is mind, SolarMetric uses the JDO extension mechanism to add inverse metadata to the JDO metadata file. For more information on metadata, consult Chapter 6, Metadata of the Kodo JDO Reference Guide.

    Add the following code immediately before the "</package>" line in the package.jdo file.

    <class name="Rabbit" persistence-capable-superclass="Animal" >
        <field name="parents">
            <collection element-type="Rabbit"/>
        <field name="children">
            <collection element-type="Rabbit"/>
            <extension vendor-name="kodo" key="inverse-owner" value="parents"/>
  3. Enhance the Rabbit class.

    jdoc Rabbit.java
  4. Refresh the object-relational mappings and database schema.

    mappingtool -action refresh Rabbit.java

Now that we have a Rabbit class, let's get some preliminary rabbit data into the database.

  1. Create some rabbits.

    Run the following commands a few times to add some male and female rabbits to the database:

    java tutorial.AnimalMaintenance add Rabbit <name> false
    java tutorial.AnimalMaintenance add Rabbit <name> true

    Now run some breeding iterations.

    java tutorial.Rabbit breed 2
  2. Look at your new rabbits.

    java tutorial.AnimalMaintenance list Rabbit
    java tutorial.AnimalMaintenance details Rabbit ""