2017-07-18 68 views
6

Làm cách nào để triển khai nhiều quan hệ với nhiều thư viện Android Room Persistence Library?Làm cách nào để thực hiện quan hệ nhiều với nhiều thư viện Android Room Persistence?

Một người dùng có thể có một hoặc nhiều thiết bị & Một thiết bị có thể được sở hữu bởi một hoặc nhiều người dùng.

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 

} 
+0

Mã của bạn dường như thực hiện quan hệ M: N, với 'UserDevice' biểu thị mối quan hệ. – CommonsWare

Trả lời

1

Giả sử một lỗi đánh máy trong UserDevice nên id là Long thay vì String:

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

Bạn có thể thử:

@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); 
} 
0

Bạn có một lỗi đánh máy trong @ Truy vấn

@Query("select * from user where user_id = :id") 
User getUserById(long id); 
Các vấn đề liên quan