我有两个对象:User
和UserType
。两者都从REST服务作为列表加载,并存储在单独的表中。
REST服务发送的User
对象包含一个 typeId ,它是UserType
的 id 。当我从数据库中加载UserType
时,应该加载User
对象。我该怎么做?
注意:
@Embedded
用户类型会将用户类型存储在用户数据库中。我宁愿有单独的桌子@Relation
旨在返回UserTypes列表,因此这不适合模型。@TypeConverter
:当我保存一个User时,其UserType对象将被简化为 id 。当我加载该用户时, id 将被UserType替换。这里的问题是,REST服务仅发送一个 typeId ,这意味着对于接收列表中的每个用户,在保存它之前,我需要获取UserType并将其设置在用户上,允许TypeConverter将此UserType转换回其ID。用户:
@Entity(tableName = "users",
foreignKeys = @ForeignKey(
entity = UserType.class,
parentColumns = "id",
childColumns = "typeId",
onDelete = ForeignKey.SET_NULL,
onUpdate = ForeignKey.CASCADE),
indices = @Index("typeId"))
public class User {
@PrimaryKey
@SerializedName("Id")
protected long id = -1;
@SerializedName("Password")
private String password;
@SerializedName("FirstName")
private String firstName;
@SerializedName("LastName")
private String lastName;
@SerializedName("GsmNumber")
private String gsmNumber;
@SerializedName("BirthDay")
private Date birthDay;
@SerializedName("TypeId")
private long typeId;
// ???
private UserType userType;
public User() {
}
// getters and setters
}
@Dao
public interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(User u);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(List<User> us);
@Delete
void delete(User u);
@Delete()
void delete(List<User> us);
@Query("SELECT * FROM users WHERE id = :id")
User load(long id);
@Query("SELECT * FROM users")
LiveData<List<User>> getAll();
}
UserType:
@Entity(tableName = "usertypes")
public class UserType {
private int color;
public UserType() {
}
// getters setters
}
@Dao
public interface UserTypeDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(UserType t);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(List<UserType> ts);
@Delete
void delete(UserType t);
@Delete()
void delete(List<UserType> ts);
@Query("SELECT * FROM usertypes WHERE id = :id")
UserType load(long id);
@Query("SELECT * FROM usertypes")
LiveData<List<UserType>> getAll();
}