saving object with one to one relationship

I’ve got a one to one relationship between 2 Tables (A,B).

I usually create a new instance of A and add a new instance of B.
Then I save A, all fine.

Now consider I’d like to save a new instance of A but add an existing instance of B this time.
I retrieve object B from the Backend, add it to object A and the save object A.

The problem is that this way, a new instance of object B is being created. (redundancies)

Just to test this i switched the id of object B to unique.
In this case I get: BackendlessException{ code: ‘36’, message: ‘Duplicate entry’ }

How to overcome this issue? Am I misunderstanding something?
Is there a way to make a “create OR update” operation?

regards
Jens

Hi Jens,

Do you do it in JavaScript?

Mark

Java (Android)

Do you have the following field in your B class?:

public String objectId

It can also be declared through public getter/setter:

private String objectId;


public void setobjectId( String objectId )
{
  this.objectId = objectId;
}


public String getobjectId()
{
  return objectId;
}

Mark

Yes, I do.
I’ve created both classes via backendless code generation.

Hi Jens,

Sorry, I could reproduce the problem. Here’s my code:

package com.mbaas;


import com.backendless.Backendless;


import java.util.ArrayList;
import java.util.List;


public class SaveRelation
{
  public static void main( String[] args ) throws Exception
  {
    Backendless.initApp( APP_ID, SECRET_KEY, "v1" );


    // STEP 1 - run this method first
    // initialSetup();


    // STEP 2 - if you run the program more than once, make sure to comment out STEP1
    saveRelationWithExistingChild();
  }


  private static void saveRelationWithExistingChild()
  {
    Person person = new Person();
    person.setName( "Bob" );


    Address address = Address.findFirst();
    List<Address> addresses = new ArrayList<Address>();
    addresses.add( address );
    person.setAddresses( addresses );
    person.save();
  }


  private static void initialSetup()
  {
    Person person = new Person();
    person.setName( "Bob" );


    Address address = new Address();
    address.setCity( "Dallas" );
    List<Address> addresses = new ArrayList<Address>();
    addresses.add( address );
    person.setAddresses( addresses );
    person.save();
  }
}

I also used code created by code generator. The schema for my tables looks like this:

Person table:
http://support.backendless.com/public/attachments/1f320f62f87fffa3e38af65f3f45e2bd.jpg</img>

Address table:
http://support.backendless.com/public/attachments/6d0fd899727ac07de5a3681599c862e3.jpg</img>

How is this different from what you’re doing?

Regards,
Mark

Hey Mark,

problem was that I fetched the object in another function and passed it over to the “save” function. Putting both in one place solved the issue.

However, I went down the road and implemented a custom Service to handle such things.