Chapter 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 tutorial.jdo

    The Rabbit class above contains a many-to-many relationship, between parents and children. From the Java side of things, a JDO 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 class. The snippet below should be inserted into the tutorial.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 has used the JDO extension mechanism to add inverse metadata to the JDO metadata file. For more information on metadata, consult the metadata section of the Kodo JDO Reference Guide.

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

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

    jdoc tutorial.jdo (or jdoc Rabbit.class)

  4. Refresh the database

    schematool -action refresh tutorial.jdo (or schematool -action refresh Rabbit.class)

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

  1. Create some rabbits

    Run java tutorial.AnimalMaintenance add Rabbit <name> false and java tutorial.AnimalMaintenance add Rabbit <name> true a few times to add some male and female rabbits to the database; then run java tutorial.Rabbit breed 2 to run some breeding iterations.

  2. Look at your new rabbits

    Run java tutorial.AnimalMaintenance list Rabbit and java tutorial.AnimalMaintenance details Rabbit to look at the contents of the database.