How to implement a many to many relations with Android Room Persistence Library?

Viewed 1920

How to implement a many to many relations with Android Room Persistence Library?

One user may have one or many devices & One device may be owned by one or many users.

User device

@Entity
public class User {
  public @PrimaryKey Long id;
  public String userName;
}

@Dao
public interface UserDao {
  @Query("select * from user") List<User> getAllUsers();

  @Query("select * from user where id = :id")
  User getUserById(long id);
}

@Entity
public class Device {

   public @PrimaryKey Long id;
   public String name;

}


@Dao
public interface DeviceDao {

    @Query("select * from device")
    List<Device> getAllDevices();
}


@Entity
public class UserDevice {
    public String userId;
    public String deviceId;
}

@Dao
public interface UserDeviceDao {

// List all devices by userId
// List all users by deviceId

}
2 Answers
Related