如何与Android Room Persistence Library实现多对多的关系?

时间:2017-07-18 07:51:18

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

如何与Android Room Persistence Library实现多对多的关系?

一个用户可能拥有一个或多个设备&一个设备可以由一个或多个用户拥有。

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 个答案:

答案 0 :(得分:1)

假设UserDevice中的拼写错误,那么ID为Long而不是String

@Entity(primaryKeys = {"userId", "deviceId"})
public class UserDevice {
    public Long userId;
    public Long deviceId;
}    

你可以尝试:

@Dao
public interface UserDeviceDao {

    // List all devices by userId
    @Query("select * from device "
           " inner join userdevice on device.id = userdevice.deviceId " 
           " where userdevice.userId = :userId")
    List<Device> getUserDevices(Long userId);

    // List all users by deviceId
    @Query("select * from user "
           " inner join userdevice on user.id = userdevice.userId "
           " where userdevice.deviceId = :deviceId")
    List<User> getDeviceUsers(Long deviceId);
}

答案 1 :(得分:-1)

@Query

中有拼写错误
@Query("select * from user where user_id = :id")
User getUserById(long id);