Categories
Mastering Development

How to specify foreign relations with Embedded Entity

I’ve a student table and an embedded type address.

Student Schema

+----+------+------------+
| id | name | address_id |
+----+------+------------+
|  1 | John |          1 |
|  2 | Jane |          2 |
+----+------+------------+

Address Schema

+----+------------------+
| id |     addressLine  |
+----+------------------+
|  1 | 123 Acme Street  |
|  2 | 456 Beach Street |
+----+------------------+

Student Entity

@Entity(tableName = "student")
data class Student(
     @PrimaryKey var id: Long, 
     var name: String?, 
     @Embedded var address: Address
)

Address Entity

@Entity(tableName = "address")
data class Address(
     @PrimaryKey var id: Long, 
     val addressLine: String
)

DAO Interface

@Dao
interface StudentDao {

    @Query("SELECT * FROM student WHERE id = :id INNER JOIN address ON student.address_id = address.id")
    fun findById(id: Long): Student
}

Issue: Current unable to populate the Embedded address of the Student.

Leave a Reply

Your email address will not be published. Required fields are marked *