In another post, we describe how to add columns/properties to a Backendless table/class using Backendless Console. The types of properties reviewed in that post were all primitive: string, numbers, dates or boolean values. In addition to these data types, Backendless also supports relationships between objects stored in its persistent storage.
These relationships are classic composition types in the object-oriented world. That means a table may declare a property (column) that references either one or a collection of objects from another (or the same) table. When these objects are materialized on the client-side (assuming the language supports object-oriented programming), the properties simply reference related objects.
Consider the following example:
There are two classes Restaurant and Location. An instance of Restaurant contains a collection of Location objects:
package com.mbaas.samples.dto; public class Location { private String streetAddress; private String city; private String phoneNumber; public String getStreetAddress() { return streetAddress; } public void setStreetAddress( String streetAddress ) { this.streetAddress = streetAddress; } public String getCity() { return city; } public void setCity( String city ) { this.city = city; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber( String phoneNumber ) { this.phoneNumber = phoneNumber; } }
Restaurant class:
package com.mbaas.samples.dto; import java.util.ArrayList; public class Restaurant { private String name; private ArrayList<Location> locations; public String getName() { return name; } public void setName( String name ) { this.name = name; } public ArrayList<Location> getLocations() { return locations; } public void setLocations( ArrayList<Location> locations ) { this.locations = locations; } }
Backendless stores instances of these classes in tables named after the class name: Restaurant and Location. If at the time when an instance is being saved the table does not exist, Backendless creates it automatically. We refer to that approach as “code first”. However, you can also pre-create the tables and explicitly declare the relationships between them. This “schema first” approach has its own benefits which will be discussed at a later point.
The instructions below demonstrate how to create the same relationship which you can see in the code above. It assumes you already created the Restaurant and Location tables:
Once the relationship is declared, you can use it to link objects together using the Console, it will also be used by the Backendless code generator when creating client-side classes based on storage schema.