在ROOM数据库中联接表

时间:2018-07-05 08:34:27

标签: android sqlite android-room android-architecture-components android-database

这是我的第一个ROOM实施。我有一个 User 类,该类具有宠物列表作为其成员变量之一。

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


Public class Pets {
    String id;
    String type;
}

如何通过以下JSON为Room Database创建其Entity和DAO类?

{  
  "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类

@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个带有各自宠物的用户?

1 个答案:

答案 0 :(得分:2)

这是一个多对多关系,因此您必须创建一个联接表: 带有petId和userId的UserPetsJoin表; 在这里,您可以找到一个很好的主题来说明您的情况: https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a