A file based persistence mechanism is now available that writes out the
details of objects to files using XML. Each main object is stored in an
individual file and can, therefore, be easily read or modified. An example
is shown below (of a Location object from the ECS
application).
<?xml version="1.0"?> <naked-object type="ecs.delivery.Location" id="8"> <value field="Known As" value="Home"/> <association field="City" type="ecs.delivery.City" ref="2"/> <value field="Street Address" value="234 Main Drive"/> <association field="Customer" type="ecs.delivery.Customer" ref="9"/> </naked-object>
The root element specifies what type of object it is for and what its object id (oid) is. Each subelement is for the objects fields and specifies the field and its content.
Using this simple object store is a good way to provide persistence to exploratory applications. (It is not advisable to use this for real applications as its performance will diminish as the number of objects increases.)
The first step is to override the installObjectStore
method and instantiate an XmlObjectStore object. The
constructor takes one parameter, which details where the files are to be
stored. A second constructor that takes no parameters will store the files
in a default directory called xml. Next time the application
is started a suitable directory will be created and all the objects that
you create (as a user) will be persisted. The objects will, therefore, be
available when you restart the application later.
protected NakedObjectStore installObjectStore() {
return new XmlObjectStore("data");
}
Now there is no reason to programmatically set up any objects unless -
like the ECS cities - the system does not allow the user to do so. In
such a case the objects need to be added to the the first time the
application is started and not each time it is run. To ensure this check
for any instances using the hasNoInstances method as shown
below. This will ensure that new city objects are not created if there are
already city instances, i.e. it will work when there are none. After this
method has been called the Exploration class will make each
object created via the createInstance method
persistent.
public void initObjects() throws ObjectStoreException {
if(hasNoInstances(City.class)) {
String[] cities =
{
"New York",
"Boston",
"Washington",
"Chicago",
"Tampa",
"Seattle",
"Atlanta" };
for (int i = 0; i < cities.length; i++) {
City newCity = (City) createInstance(City.class);
newCity.getName().setValue(cities[i]);
}
}
}
Copyright (c) 2002 - 2004 nakedobjects.org
You may print this document for your own personal
use, or you may copy it in electronic form for access within your
organisation, provided that this notice is preserved.