Skip to content

One to one relationship

Ravi Teja Gudapati edited this page Feb 19, 2019 · 8 revisions

One to one relationship maps one record in a table to another record in referred table.

In Jaguar, one-to-one mapping is performed using [HasOne][HasOne] and [BelongsTo][BelongsTo] annotations. Let us take an user-address example. Each user has an address.

Parent model

The linked field in the parent model is annotated with HasOne annotation. In this case, User is linked to Address using the address field. HasOne takes the bean of the referred table as the argument. In this case, AddressBean

class User {
  @PrimaryKey(length: 50)
  String id;

  @Column(length: 50)
  String name;

  @HasOne(AddressBean)
  Address address;

  User({this.id, this.name, this.address});
}

Referred table

The foreign key in the referred table should be annotated by BelongsTo annotation. In this case, userId is the foreign key that is used to link a user to the address by user's id. BelongsTo annotation takes the bean of the parent table as the argument. In this case, UserBean

class Address {
  @PrimaryKey(length: 50)
  String id;

  @Column(length: 150)
  String street;

  @BelongsTo(UserBean)
  String userId;

  Address({this.id, this.street, this.userId});
}

Beans

Templates for UserBean and AddressBean should be written with members AddressBean addressBean and UserBean userBean respectively. The generated bean logic will use these fields to perform operation on the linked tables.

@GenBean()
class UserBean extends Bean<User> with _UserBean {
  UserBean(Adapter adapter)
      : addressBean = AddressBean(adapter),
        super(adapter);

  final AddressBean addressBean;

  String get tableName => 'oto_simple_user';
}

@GenBean()
class AddressBean extends Bean<Address> with _AddressBean {
  UserBean _userBean;
  UserBean get userBean => _userBean ??= UserBean(adapter);

  AddressBean(Adapter adapter) : super(adapter);

  String get tableName => 'oto_simple_address';
}

Operations

Cascaded inserts and upserts

TODO

Cascaded delete

TODO

Cascaded updates

TODO

Auto preload child field

TODO

Manual preload child field

TODO

Find parent by child instance

TODO

Clone this wiki locally