OneToOne simple relationship
See original GitHub issueHello.
I spent lot of time finding the way to implement simple and elegant OnToOne relation for two models. But the only way to make it possible I described here https://github.com/Raizlabs/DBFlow/issues/216#issuecomment-120721936
My models actually are DTOs which means I have a pre-defined structure. Fields annotated with @Expose are handled by Retrofit serializers (Gson). Each User object has an UserProfile. UserProfile can not live without referenced User.
User.java
@Table(tableName = "Users", databaseName = "mydb")
@ModelContainer
public class User extends BaseModel {
@Column(name = "id")
@PrimaryKey(autoincrement = true)
long id;
@Expose
@SerializedName("id")
@Column(name = "userId")
String userId;
@Expose
UserProfile profile;
}
UserProfile.java
@Table(tableName = "UserProfiles", databaseName = "mydb")
public class UserProfile extends BaseModel {
@Column(name = "id")
@PrimaryKey(autoincrement = true)
long id;
@Expose
@Column(name = "firstName")
String firstName;
@Expose
@Column(name = "lastName")
String lastName;
}
The simple way means that I do not need to save or load UserProfile separately. I want to load a user only. The expected result should be:
UserProfile profile = new UserProfile();
User user = new User();
user.setUserId("133456789");
user.setUserProfile(profile);
user.save(); // saves also a userProfile
// load
User user = new Select().from(User.class).querySingle();
user.getUserProfile(); // not null, loaded from DB
// modify
user.getUserProfile().setFirstName("john");
user.save(); // saves also a userProfile
// delete
user.delete(); // deletes user and associated userProfile
Any suggestions?
With respect, Gennadi Kudrjavtsev
PS. I tried suggested method by combining OneToMany and ForeignKey but this caused circular queries (https://github.com/Raizlabs/DBFlow/issues/322#issuecomment-120845545)
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
a little more info regarding putting that ‘@ForeignKey’ would be really helpful in removing the confusion of all this One to One relation in dbFlow. And a use case example just like ydanneg has described above. Thanx
solution would have been to use a
@ForeignKey