Slim3 Datastore‎ > ‎Relationships‎ > ‎

Unidirectional Many-to-One Relationships

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

The following example defines an Employee(many side) model and a Department(one side) model:

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

   
// ...
}

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

   
// ...
}

Let's add a many-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<Department> departmentRef;

   
// ...
}

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

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

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

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

private
ModelRef<Department> departmentRef = new ModelRef<Department>(Department.class);
   
// ...
}


Now let's create an employee and a department.
Department department = new Department();
...
Employee employee = new Employee();
...
employee.getDepartmentRef().setModel(department);
Datastore.put(department, employee);

You can get an employee and a department. The relationship is loaded lazily.
Key employeeKey = ...;
Employee employee = Datastore.get(Employee.class, employeeKey);
Department department = employee.getDepartmentRef().getModel();

Next...

Continue to Bidirectional One-to-Many Relationships.


Comments