Slim3 Datastore‎ > ‎Relationships‎ > ‎

Unidirectional One-to-One Relationships

You create a unidirectional one-to-one relationship between two models.

The following example defines an Employee model and an Address model:

@Model
public
class Employee {
   
@Attribute(primaryKey = true)
   
private Key key;

   
// ...
}

@Model
public
class Address {
   
@Attribute(primaryKey = true)
   
private Key key;

   
// ...
}

Let's add a one-to-one relationship with a foreign key to Employee.
To define it, use ModelRef<ModelType>.
@Model
public
class Employee {
   
@Attribute(primaryKey = true)
   
private Key key;

private ModelRef<Address> addressRef;

   
// ...
}

The following error will be shown for addressRef field:
[SLIM3GEN1011] The getter method is not found.

Use quick fix(hold down CTRL+1) and select "Create getter and setter for 'addressRef'".

The following error will be shown for setAddressRef method:
[SLIM3GEN1041] The setter method for the field[addressRef] is not allowed. Define the field as follows:
ModelRef<Address> addressRef = new ModelRef<Address>(Address.class);

As the message says, define addressRef field and delete setAddressRef method.
@Model
public
class Employee {
   
@Attribute(primaryKey = true)
   
private Key key;

private ModelRef<Address> addressRef = new ModelRef<Address>(Address.class);

   
// ...
}


Now let's create an employee and an address.
Address address = new Address();
...
Employee employee = new Employee();
...
employee.getAddressRef().setModel(address);
Datastore.put(address, employee);

You can get an employee and an address. The relationship is loaded lazily.
Key employeeKey = ...;
Employee employee = Datastore.get(Employee.class, employeeKey);
Address address = employee.getAddressRef().getModel();

Next...

Continue to Bidirectional One-to-One Relationships.


Comments