6

如何使用 Android Room Persistence Library 实现多对多关系?

一位用户可能拥有一台或多台设备,而一台设备可能由一位或多位用户拥有。

用户设备

@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

}
4

2 回答 2

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);
}
于 2017-07-18T15:48:07.310 回答
-2

您在@Query 中有错字

@Query("select * from user where user_id = :id")
User getUserById(long id);
于 2017-09-05T20:26:49.010 回答