Backendless Support
 

Recursive object references in persistence objects

A recursive reference is when an object is either directly or indirectly references itself. This design pattern happens rather frequently in applications and quite often distributed systems do not handle it gracefully. 

This statement doesn't refer to Backendless as it fully supports object recurrence - it is easily proved by the following example.

                                       For Objective-C and Swift implementations CLICK HERE

Consider the following class (Android and Plain Java):

package com.mbaas.sample;
import java.util.List;
public class Person
{
 public String name;
 public int age;
 public Person mom;
 public Person dad;
 public List<Person> children;
}

Not only the class references itself through the "mom" and "dad" fields, it also includes the "children" field which may creates a recursive dependency. For example, suppose a person named Bobby has mom and dad named Jennifer and Richard accordingly. Both objects representing the mother and the father refer back to Bobby through the "children" field. The code below demonstrates that structure and saving it in Backendless using the Data storage AP.

Asynchronous API (Android and Plain Java):
Person me = new Person();
me.name = "Bobby";
me.age = 13;
Person mom = new Person();
mom.name = "Jennifer";
mom.age = 40;
mom.children = Arrays.asList( new Person[] { me } );
Person dad = new Person();
dad.name = "Richard";
dad.age = 41;
dad.children = Arrays.asList( new Person[] { me } );
me.mom = mom;
me.dad = dad;
Backendless.Data.of( Person.class ).save( me, new AsyncCallback<Person>()
{
 @Override
 public void handleResponse( Person person )
 {
 System.out.println( "Person object has been saved" );
 }
 @Override
 public void handleFault( BackendlessFault backendlessFault )
 {
 System.out.println( "Server reported an error " + backendlessFault.getMessage() );
 }
} );
Synchronous API (Plain Java only):
Person me = new Person();
me.name = "Bobby";
me.age = 13;
Person mom = new Person();
mom.name = "Jennifer";
mom.age = 40;
mom.children = Arrays.asList( new Person[] { me } );
Person dad = new Person();
dad.name = "Richard";
dad.age = 41;
dad.children = Arrays.asList( new Person[] { me } );
me.mom = mom;
me.dad = dad;
Backendless.Data.of( Person.class ).save( me );

Once a developer runs the code, the data structure created in Backendless fully reflects the relationships created in the code. Explore a screenshot of the Person data table: 

The structure in the data table may appear complex, however, it fully resembles the object hierarchy created in the code. Bobby has mom Jennifer and dad Richard. Both Jennifer and Richard have a child with the object ID from Bobby.

This is rather a complex process which appears to become a simple process with Backendless.

Is article helpful?