Skip to content
This repository has been archived by the owner on May 1, 2020. It is now read-only.

How to use model classes

Sam Bosley edited this page Sep 22, 2015 · 6 revisions

Model classes are objects representing rows in a SQLite table (thereby also defining the schema for that table). Typically, you will want the SquiDB code generator to write your model classes for you using spec files. Classes representing a row in a table extend TableModel, while classes representing a row in a view or subquery result extend ViewModel (see Model specs for SQL views for more information about ViewModels). Both TableModel and ViewModel extend from the base class AbstractModel.

Model classes declare one or more constants using the provided Property classes. Each such constant declaration corresponds to a typed column in the table.

public class Person extends TableModel {

    public static final LongProperty ID = new LongProperty(/*args*/);

    public static final StringProperty FIRST_NAME = new StringProperty(/*args*/);

}

These Property declarations serve as the table schema and integrate with SquiDB's query language to allow you to easily construct queries, where clauses, etc. that reference the corresponding columns.

AbstractModel, which all model objects inherit from, provides typesafe get() and set() methods that operate on properties. For example:

Person p = new Person();
// Set's this person's firstName property to "Sam".
// Calling set() with a StringProperty only allows a String value to be set
// Similar rules apply for all the other Property types
p.set(Person.FIRST_NAME, "Sam");
// Calling get() on a StringProperty will always return a String
String firstName = p.get(Person.FIRST_NAME);

While this style of getting/setting properties works, we don't believe that this code is very user friendly. It's verbose and not entirely easy to read. For convenience, the SquiDB code generator will automatically generate named getters and setters for each declared property in the ModelSpec class. For example, the above Person class would also have:

public class Person extends TableModel {
    ...

    public String getFirstName() {
        return get(FIRST_NAME);
    }

    public Person setFirstName(String firstName) {
        set(FIRST_NAME, firstName);
        return this;
    }

}

This makes the above code sample much cleaner to write:

Person p = new Person();
p.setFirstName("Sam");
String firstName = p.getFirstName();

Model classes also define Table objects that are used when constructing queries and for initializing the database.

NOTE: Model classes are NOT thread safe! Therefore we do not recommend writing to an instance of an object from multiple threads. If you must, take care to use your own synchronization mechanisms. Reading from a shared instance is pretty safe, assuming the object has been populated and won't be written to by other threads.


See also: