The next thing to do is decide if we want to allow JPOX to generate the identities of our objects, or whether we want to do it ourselves. In our case we will allow JPOX to create the identities for our Packs, but since we know which Cards are in a pack we want to give them an identity based on the suit and the number. This allows us to give examples of both datastore identity and application identity. In the case of Pack there is nothing more to code since JPOX will handle the identities. With Card however we now need to define a definition of the primary key. With JDO we must define a primary key class. In our case we want our primary key to be a composite of suit and number, so we define a primary key as follows
public static class CardKey
{
public String suit;
public String number;
/**
* Default constructor (mandatory for JDO).
*/
public CardKey()
{
}
/**
* String constructor (mandatory for JDO).
**/
public CardKey(String str)
{
StringTokenizer toke = new StringTokenizer (str, "::");
str = toke.nextToken ();
this.suit = str;
str = toke.nextToken ();
this.number = str;
}
/**
* Implementation of equals method (JDO requirement).
**/
public boolean equals(Object obj)
{
if (obj == this)
{
return true;
}
if (!(obj instanceof CardKey))
{
return false;
}
CardKey c=(CardKey)obj;
return suit.equals(c.suit) && number.equals(c.number);
}
/**
* Implementation of hashCode (JDO requirement)
*/
public int hashCode ()
{
return this.suit.hashCode() ^ this.number.hashCode();
}
/**
* Implementation of toString that outputs this object id's PK values.
* (JDO requirement).
**/
public String toString ()
{
return this.suit + "::" + this.number;
}
}
We decide that we don't want to use this class as an external object so we make it an inner class of our Card class. This is optional. You could have it as a class used elsewhere if you wish. Continue on to the next part of this JPOX Example |