Joining tables in a ROOM database

Abhinav Tyagi picture Abhinav Tyagi · Jul 5, 2018 · Viewed 9.6k times · Source

This is my first ROOM implementation. I have a User class which has a list of Pets as one of its member variables.

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


Public class Pets {
    String id;
    String type;
}

How to create its Entity and DAO classes for Room Database from the following JSON?

{  
  "users":[  
    {  
      "id":"as123",
      "name":"John",
      "pets":[  
        {  
          "id":"p123",
          "type":"dog"
        }
      ]
    },
    {  
      "id":"as343",
      "name":"Mark",
      "pets":[  
        {  
          "id":"p324",
          "type":"dog"
        },
        {  
          "id":"p254",
          "type":"cat"
        }
      ]
    }
  ]
}

I have created the following but not sure how to create a correct column or Join these tables.

Entity Classes

@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
}

How can I get a List of users with all of their respective pets?

Answer

Amine Nokra picture Amine Nokra · Jul 5, 2018

This is a many-to-many relation so you have to create a join table: UserPetsJoin table with the petId and userId; Here you can find a good topic explaining you're same situation: https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a