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.
@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
}
Android one to many in room explanation: Add the @Relation annotation to the instance of the child entity, with parentColumn set to the name of the primary key column of the parent entity and entityColumn set to the name of the column of the child entity that references the parent entity's primary key.
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite. In particular, Room provides the following benefits: Compile-time verification of SQL queries.
Room is a persistent library that is part of the Android jetpack. It is built on top of SQLite. The room persistent library has many advantages over raw SQLite.
Assuming a typo in UserDevice
so id's are Long
instead of String
:
@Entity(primaryKeys = {"userId", "deviceId"})
public class UserDevice {
public Long userId;
public Long deviceId;
}
You could try:
@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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With