连接 ROOM 数据库中的表

Joining tables in a ROOM database

这是我的第一个 ROOM 实现。我有一个 User class,它有一个 Pets 列表作为其成员变量之一。

public class User {
    String id;
    String name;
    List<Pet> pets;
}


Public class Pets {
    String id;
    String type;
}

如何从以下 JSON?

创建 Room 数据库的实体和 DAO classes
{  
  "users":[  
    {  
      "id":"as123",
      "name":"John",
      "pets":[  
        {  
          "id":"p123",
          "type":"dog"
        }
      ]
    },
    {  
      "id":"as343",
      "name":"Mark",
      "pets":[  
        {  
          "id":"p324",
          "type":"dog"
        },
        {  
          "id":"p254",
          "type":"cat"
        }
      ]
    }
  ]
}

我创建了以下内容,但不确定如何创建正确的列或加入这些表。

实体类

@Entity(tableName = "user")
public class User {

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = "id")
    String id;

    @Nullable
    @ColumnInfo(name = "name")
    String name;

    List<Pets> pets; // how to set type for Pets
}

@Entity(tableName = "pets",
    foreignKeys = @ForeignKey(entity = User.class,
    parentColumns = "id",
    childColumns = "userId",
    onDelete = CASCADE))
Public class Pets {

    @PrimaryKey
    @NonNull
    @ColumnInfo(name = "id")
    String id;

    @Nullable
    @ColumnInfo(name = "type")
    String type;

    @NonNull
    @ColumnInfo(name = "userId")
    String userId; // for accessing pets of a user
} 

DAO classes

@Dao
public interface PetsDAO {

    @Insert
    void insert(Pets pets);

    @Update
    void update(Pets... pets);

    @Delete
    void delete(Pets... pets);

    @Query("SELECT * FROM pets WHERE id=:userId")
    List<Pets> getPetsForUser(final String userId);
}

@Dao
public interface UserDAO {

    @Insert
    void insert(User pets);

    @Update
    void update(User... pets);

    @Delete
    void delete(User... pets);

    @Query("SELECT * FROM user)
    List<User> getAllUsers(); // should return list of users with all their pets
}

如何才能让 List 的用户拥有各自的宠物?

这是多对多关系,因此您必须创建连接 table: 使用 petId 和 userId 的 UserPetsJoin table; 在这里您可以找到一个很好的主题来解释您的相同情况: https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a