Home > Blockchain >  Android Room one to many relationship
Android Room one to many relationship

Time:02-06

I'm attempting to create a one-to-many relationship where each instance of user corresponds to zero or more instances of role entity.

Problem: UserRoleJunction is having issues in the @Relation for both parentColumn (user) and entityColumn (role)

I didn't reach to DAO implementation yet because of the error.

user

 ---- ---------- ---------- 
| id | username |   name   |
 ---- ---------- ---------- 
|  1 | johndoe  | John Doe |
|  2 | janedoe  | Jane Doe |
 ---- ---------- ---------- 

data class

@Entity(tableName = "user")
data class User(
    @PrimaryKey (autoGenerate = true) 
    var id: Long,
    var username: String? = null,
    var name: String? = null)

role

 ---- ---------- 
| id |   name   |
 ---- ---------- 
|  1 | Sales    |
|  2 | Shipping |
|  3 | Accounts |
 ---- ---------- 

data class

@Entity(tableName = "role")
data class Role(
    @PrimaryKey(autoGenerate = true)
    var id: Long,
    var name: String? = null)

user_role Join or CrossRef Table

 --------- --------- 
| user_id | role_id |
 --------- --------- 
|       1 |       1 |
|       1 |       3 |
|       2 |       1 |
 --------- --------- 

data class

@Entity(tableName = "user_role", primaryKeys = ["user_id", "role_id"])
data class UserRoleJoin( // CrossRef
    @ColumnInfo(name = "user_id") var userId: Int,
    @ColumnInfo(name = "role_id") var roleId: Int)

Junction data class

data class UserRoleJunction (
    @Embedded var user: User,
    @Relation(
        parentColumn = "id", // User -> error: see below
        entityColumn = "id", // Role -> error: see below
        associateBy = Junction(UserRoleJoin::class)
    )
    var roles: List<Role>
)

Error 1 UserRoleJunction

parentColumn

error: Cannot find the parent entity referencing column id in the junction UserRoleJoin. Options: user_id, role_id

entityColumn

error: Cannot find the child entity referencing column id in the junction UserRoleJoin. Options: user_id, role_id

I did try substituting user_id and role_id as per the error messages but it keeps throwing similar errors like above.

Error 2 UserRoleJunction

Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).

CodePudding user response:

When using a association/junction there are 4 columns involved.

Two parents and two children. The parentColumn and entityColumn at the @Relation level define the columns in the @Relation (User) and the @Embedded (Role) tables.

The Junction is used to specify the respective columns in the junction table itself, these have been omitted and are the cause of the errors.

So you should be using:-

Junction(UserRoleJoin::class, parentColumn = "user_id", entityColumn = "role_id")
  • Related