April 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Castor Cures Your Data Binding Ills, Page 2

  • February 27, 2003
  • By Thomas Hammell, Thomas Hammell
  • Send Email »
  • More Articles »

Java SQL Binding

Castor's other main API is used to persist Java object to database tables. This API is very similar to JDO. In fact, the main class used to do conversion between object and database table is the JDO class. Before we can start using this class, however, we first have to determine how to map each of our Java objects to a specific database table. Of course, object-relational mapping is a fairly complex subject in itself that can not be covered properly in this article. For a more detailed discussion of object-relation mapping, see the resources at the end of the article.

To keep our example simple, we are going to use the same classes that we used for the XML example (DirectoryNode and FileNode). To map these objects to a database, we must first create a table that corresponds to each object. The FileNodes table contains entries for the name of the file, the size of the file, whether the file is locked or not, and a parent field that is used to link the file to its parent directory. The DirNodes table contains entries for name of the directory and a parent field, which can be used to link this directory to its parent.

Figure 2: Database tables for the File and Directory Node objects

Now that we have the tables and objects defined, we need to create a mapping file that Castor will use to transfer the objects to/from the database. Unlike Castor XML, Castor JDO requires a mapping file to be used.

<mapping>
  <class name="DirectoryNode" identity="name">
    <description>Default mapping for class
                         DirectoryNode</description>
    <map-to table="dirnodes"/>
    <field name="name" type="string" required="false"
                       direct="false" transient="false">
      <sql name="name" type="varchar"/>
    </field>
    <field name="parentName" type="string">
      <sql name="parent" type="varchar"/>
    </field>
    <field name="childList" type="FileNode" required="false"
                            collection="vector"
                            get-method="getChildList"
                            set-method="setChildList">
      <sql many-key="parent"/>
    </field>
  </class>
  <class name="FileNode" identity="name">
    <description>Default mapping for class FileNode</description>
    <map-to table="filenodes"/>
    <field name="name" type="string">
      <sql name="name" type="varchar"/>
    </field>
    <field name="locked" type="boolean" get-method="getLock"
                         set-method="setLock">
      <sql name="locked" type="bit"/>
    </field>
    <field name="filesize" type="integer">
      <sql name="size" type="integer"/>
    </field>
    <field name="parentName" type="string">
      <sql name="parent" type="varchar"/>
    </field>
  </class>
</mapping>

The mapping file for mapping objects to a database is very similar to the mapping file Castor uses for XML mapping. In fact, the two mapping files can be combined into one file, if desired.

There are elements for classes and fields just like the XML mapping file. The main difference for the class element is a new attribute called "identity". This attribute is used to designate the field in this class, which will uniquely identify an instance of this class. Another way to look at this is that the identity field will be the primary key for the table that contains these objects. For our example, the identity for file and directory nodes is just the name of the node. This is the simplest type of identity, but the identity field can also be a complex type made up of multiple fields.

Inside the class element is a "map-to table" element that is used to associate the class to a table in the database. Inside the field element is an sql element that is used to associate a member variable with a column in the database table. It's important to make sure that the Java type for the field and the database type for sql element are compatible. For example, in the name field in the FileNode class, the type is String for the field element and varchar for the sql element. Likewise, for the locked field in the FileNodes class is type boolean for the field element and bit for the sql element. As long as the types are compatible, Castor will do the conversions correctly.

Besides defining how member variables for each object maps to each table, the mapping file is also used to define how the objects are connected. The sql element can either contain a many-key attribute to define a one to many relationship or a many-table attribute to define a many to many relationship.

For our example, the DirectoryNode contains a field element named childList, which is used map the DirectoryNode's childList vector to a set of FileNode entries in the FileNodes table. The sql element within the field tag uses the many-key attribute to map the DirectorNode's identity field to the FileNode's parent field thus establishing the one to may relationship between directory and file nodes (in other words, each file node will contain the name of its one parent in its parent field).

One thing to note is that the mapping defines the relationship between objects in a fairly rigid way. Even though a directory node can have children that are file or directory nodes, our mapping has limited the directory node children to be only file nodes. This was just the result of our database design. If a more complex relationship is needed between the objects, the database has to be changed accordingly. The problem is that Java objects can use inheritance and polymorphism in their design but these properties are hard to map to a database. Although there are some other tags and attributes in the mapping file that may help map these relationships, the database design is critical to allow easy conversion between objects and the database.

Now that we have the mapping file set up, we can write the code to bind the objects to the database. The first thing that needs to be created is the JDO object.

      m_JDO = new JDO();
      m_JDO.setDatabaseName("test");
      m_JDO.setConfiguration("my_database.xml);

The JDO object requires two things to be set before it can be used: the database name and a configuration file. The configuration file contains information about how to connect the database as well as what mapping file to use. For more information on the configuration file, see the Castor documentation. The documentation contains a lists of databases supported along with some sample configuration files.

Once the JDO object is created and configured, it then can be used to create, read, update, or delete objects defined in the mapping file. The class that is used to do these operations is the Database class, which can be gotten from the JDO class by using the JDO.getDatabase() method. The Database class represents a connection to the database and contains most of the methods needed to interact with the database. All database operations must be performed in the context of a transaction using the Database.begin() and Database.commit() methods.

To create a new object and persist it to the database, you first need to create the object, and then call the Database.create() method to persist it to the database, as shown in the code below.

   DirectoryNode srcDir = new DirectoryNode("src");
   FileNode srcFile = new FileNode("XMLConverter.java", 5);
   FileNode xmlFile = new FileNode("rootNode.xml", 1);

   srcFile.setParentName(srcDir.getName());
   srcDir.addChild(srcFile);
   xmlFile.setParentName(srcDir.getName());
   srcDir.addChild(xmlFile);

   Database db = m_JDO.getDatabase();
   //Set auto store to true so that child nodes are also created
   db.setAutoStore(true);
   db.begin();
   db.create(srcDir);
   db.commit();

This code snippet shows some of the nice features of Castor. Even though there are three objects created, the directory node and two file nodes, you only need to call the db.create() method once for the directory node to persist all three objects to the database. This is because when AutoStore is set to true, the create() operation will create the specified object and all other related objects. You also can get this same behavior if you specify the FileNode class to be dependant on the DirectoryNode class in the mapping file. However, if do this, you cannot access the file nodes directly, but only through directory nodes. See the Castor documentation for a full explanation of this behavior.

Castor gives you a couple of ways to get objects from the database. If you know the exact object you want, you can use the load() method to get the specific object as shown in the code below.

    db.begin();
    dirNode = (DirectoryNode) db.load(DirectoryNode.class, "src");
    db.commit();

The load() method shown here takes two arguments. The first argument is the class of the object you are looking for. The second argument is the value of the identity field for this class that will uniquely identify the object.

If you want to get a group of objects from the database, you can use Castor's OQL (Object Query Language) to query the objects in the database and get back a result set. An OQL query is very similar to the sql query language except you query objects, not the underlying database tables. The query is executed as shown below. For details on OQL, see the Castor documentation.

db.begin();
OQLQuery oql = db.getOQLQuery("SELECT s FROM DirectoryNode s
                               WHERE s.name = \"src\""); 
QueryResults results = oql.execute();
while(results.hasMore())
{
    dirNode = (DirectoryNode) results.next();
    //do something with directory node
}
db.commit()

Castor caches the objects it retrieves from the database, so if the object is retrieved multiple times by different calls it only reads the object from the database once. This minimizes calls to the database and makes the process more efficient.

Updates are also easy to do. Simply make the changes to the object and call the update() method:

   DirNode.setParent("root");
   db.begin(); 
   db.update(dirNode);
   db.commit();

Updates will throw an ObjectModifiedException if the object in the database has been modified since the object was last retrieved from the database. Castor calls this dirty checking. For dirty checking to work, each object class must implement the TimeStampable interface. This interface has two methods used to set and get the timestamp when the object is retrieved or updated.

This dirty checking is useful if multiple clients are updating the same object in the database. For example, let's say one client gets an object from the database just before a second client performs an update to that object. When the first client goes to do an update, it will get an ObjectModifiedException that it can catch and then use the load() method to get a fresh version of the object from the database before doing the update. This will prevent clients from overwriting each other's changes. Castor's Database class also provides a lock method, so a client can lock an object in the database so that it can't be modified by anyone else.

Objects are deleted from the database with the remove method.

   db.begin(); 
   db.remove(dirNode);
   db.commit();

The remove method only removes the specified object and not any related objects unless the related objects have specified a dependency on the object being deleted in the mapping file.

Conclusion

There is a lot more to the Castor API than what I have shown here in these simple examples. Castor is very well documented and provides a lot of information, not only on the API but on the philosophy behind it as well as the best way to use it. I encourage you to check out the Castor Web site and explore the API on your own. Hopefully, these examples have demonstrated the usefulness of the Castor API and will give you another tool to use when mapping Java objects to XML files or databases.

Links and References

  1. Source code for all examples in this article: click here to download.
  2. Castor Web site: http://castor.exolab.org
  3. For more information on object-relational mapping, see Scott Ambler's "Mapping Objects to Relational Databases" article.

Author's Bio

Thomas Hammell is a senior developer at Hewlett-Packard and is part of the Open Call Business Unit that develops telecom networks infrastruture software. He has over 17 years of experience in developing software. Tom has published a number of articles on Java topics ranging from Swing development to Unit testing and speaks frequently on Java topics. Tom holds a Bachelor of Science in Electrical Engineering and Master of Computer Science from Steven's Institute of Technology. He may be reached at thomas_hammell@hp.com.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel