Slim3 Datastore‎ > ‎

Polymorphic Model

It is often useful to define data models as a classification hierarchy, much like how an object database can define one class of objects as a sub-class of another. Such a database can perform queries on objects of the parent class, and include objects of the sub-class in the results. The App Engine datastore does not support this kind of query natively, but you can implement it using a mechanism included with Slim3 Datastore.

For example:
@Model
public class
Contact {
...
}

@Model
public class
Person extends Contact {
...
}


@Model
public class
Company extends Contact {
...
}



Person p = new Person();
...
Datastore.put(p);

Company c = new Company();
...
Datastore.put(c);

List<Contact> list = Datastore.query(Contact.class).asList();
  // Returns both p and c.
 
// ...

List<Person> list = Datastore.query(Person.class).asList();
 
// Returns only p.
 
// ...

A sub model that extends super model are stored in the datastore with the same kind of super model, and a sub model has a property named "slim3.classHierarchyList", which stores the list of class hierarchies except root model.
When the application creates a query for sub model, the query includes a filter on the 'slim3.classHierarchyList' property that limits the results to entities created from the sub model or any subclass.

Because Polymorphic Model uses 'slim3.classHierarchyList' property to store class information, indexes for polymorphic queries must accommodate the property. The implied filter is an equality filter, and can be combined with other equality filters and inequality filters on other properties.

To create a new sub model, an application needs the following:

Double-click build.xml under the project.

In the Outline view, right-click model-controller task and select Run as > Ant Build(first item)

In the ant input dialog, input "sub-model-name extends super-model-name", and click OK button.

If your project is not refreshed automatically, in the Window menu, select Preferences > General > Workspace. Click "Refresh automatically" checkbox. Or refresh your project manually.
 

"src/tutorial/model/Person.java" and "test/tutorial/model/PersonTest.java" will appear. The part of "Person" is "sub-model-name".

Let's take a look at "src/tutorial.model/Person.java".
package slim3.demo.model;

import java.io.Serializable;

import org.slim3.datastore.Model;

@Model
public class Person extends Contact implements Serializable {

    private static final long serialVersionUID = 1L;

}


Comments