-
Notifications
You must be signed in to change notification settings - Fork 127
Advanced model spec options
Occasionally there will be times when you want to exercise greater control over your table schemas. The TableModelSpec annotation has several optional fields to help you exercise greater control over how your table is defined. See the TableModelSpec Javadocs for more information about these options.
The @ColumnSpec
annotation allows you greater control over your column definitions. Fields in your model spec can be annotated with @ColumnSpec
like so:
@TableModelSpec(className="Person", tableName="people")
class PersonSpec {
@ColumnSpec(name="fname", defaultValue="")
String firstName;
}
While this will still generate a StringProperty FIRST_NAME in the generated model file, the underlying table schema will have the column name as "fname" instead of "firstName", and will have a default value of "" instead of null. See the ColumnSpec Javadocs for all available options.
For information on primary keys and the @PrimaryKey
annotation, see this wiki page.
The @ModelMethod
annotation allows you to add additional methods to your model objects beyond the standard getters and setters for each property. ModelMethod can be applied to any public static method in your spec file, whose first argument is an instance of your generated model. For example:
@TableModelSpec(className="Person", tableName="people")
class PersonSpec {
@ColumnSpec(name="fname", defaultValue="")
String firstName;
String lastName;
@ModelMethod
public static String getFullName(Person person) {
return person.getFirstName() + " " + person.getLastName();
}
}
This will make the generated Person object have a no-argument method getFullName()
:
Person p = database.fetch(Person.class, 1);
String fullName = p.getFullName();
If you want the method to take additional arguments, just add them after the model instance argument of the static method.
Occasionally, you may want your generated models to implement particular interfaces. To declare interfaces to implement, use the @Implements
annotation:
@TableModelSpec(className = "Person", tableName = "people")
@Implements(interfaceClasses = {MySpecialInterface.class})
class PersonSpec {
...
}
The methods required for the interface can be added using ModelMethod as described above.
For interfaces that require type arguments, such as Comparable, you will need to use the @Implements.InterfaceSpec
annotation to provide a more detailed specification for the generated interface:
@TableModelSpec(className = "Person", tableName = "people")
@Implements(interfaceDefinitions = {
@Implements.InterfaceSpec(interfaceClass=Comparable.class,
interfaceTypeArgNames="com.mypackage.Person")})
// This should generate class Person implements Comparable<Person>
class PersonSpec {
...
@ModelMethod // For implementing the interface method
public static int compareTo(Person instance, Person other) {
// Implement the comparison here
}
}
See also: