Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

}
like image 870
Chathura Wijesinghe Avatar asked Jul 18 '17 07:07

Chathura Wijesinghe


People also ask

How would you insert entities with a one to many relationship in a room?

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.

What is room persistence library?

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.

What is Roomdb?

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.


1 Answers

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);
}
like image 56
Miguel A. Gabriel Avatar answered Jan 03 '23 16:01

Miguel A. Gabriel