Exploring Room Database Relationships with Use-Cases

Abhishek Pathak
3 min readAug 15, 2023

--

In modern Android app development, handling data efficiently is crucial to providing a seamless user experience. Room, a robust and intuitive persistence library by Google, simplifies database management and interaction within Android applications. One of the key features of Room is its ability to define relationships between different tables, enabling developers to create sophisticated and interconnected data structures. In this article, we’ll explore how to leverage Room to establish relationships between tables using Kotlin in Android apps.

Understanding Room Database Relationships

Room allows you to create three types of relationships between tables:

  1. One-to-One Relationship: This relationship involves a single entry in one table being associated with a single entry in another table.
  2. One-to-Many Relationship: In this case, a single entry in one table is associated with multiple entries in another table.
  3. Many-to-Many Relationship: This complex relationship involves multiple entries in both tables being related to each other.

Real-Time Example 1: Social Media App

Imagine you’re building a social media app with users, posts, and comments. Users can create posts, and each post can have multiple comments. This involves a one-to-many relationship between posts and comments.

@Entity(tableName = "user")
data class User(
@PrimaryKey val userId: Long,
val username: String,
val email: String
)

@Entity(tableName = "post", foreignKeys = [ForeignKey(entity = User::class, parentColumns = ["userId"], childColumns = ["userId"])])
data class Post(
@PrimaryKey val postId: Long,
val userId: Long,
val content: String
)

@Entity(tableName = "comment", foreignKeys = [ForeignKey(entity = User::class, parentColumns = ["userId"], childColumns = ["userId"]), ForeignKey(entity = Post::class, parentColumns = ["postId"], childColumns = ["postId"])])
data class Comment(
@PrimaryKey val commentId: Long,
val userId: Long,
val postId: Long,
val text: String
)

One-to-Many Relationship:

data class PostWithComments(
@Embedded val post: Post,
@Relation(
parentColumn = "postId",
entityColumn = "postId"
)
val comments: List<Comment>
)

Accessing Data using DAO

@Dao
interface PostDao {
@Transaction
@Query("SELECT * FROM post")
fun getPostsWithComments(): List<PostWithComments>
}

Real-Time Example 2: E-Commerce App

Let’s consider an e-commerce app with products, categories, and reviews. A product can belong to multiple categories, and each product can have several reviews. This involves a many-to-many relationship between products and categories, and a one-to-many relationship between products and reviews.

Entities:

@Entity(tableName = "product")
data class Product(
@PrimaryKey val productId: Long,
val name: String,
val price: Double
)

@Entity(tableName = "category")
data class Category(
@PrimaryKey val categoryId: Long,
val name: String
)

@Entity(tableName = "review", foreignKeys = [ForeignKey(entity = Product::class, parentColumns = ["productId"], childColumns = ["productId"])])
data class Review(
@PrimaryKey val reviewId: Long,
val productId: Long,
val rating: Int,
val comment: String
)

Many-to-Many Relationship:

data class ProductWithCategories(
@Embedded val product: Product,
@Relation(
parentColumn = "productId",
entityColumn = "categoryId",
associateBy = Junction(ProductCategoryCrossRef::class)
)
val categories: List<Category>
)

One-to-Many Relationship:

data class ProductWithReviews(
@Embedded val product: Product,
@Relation(
parentColumn = "productId",
entityColumn = "productId"
)
val reviews: List<Review>
)

Accessing Data:

@Dao
interface ProductDao {
@Transaction
@Query("SELECT * FROM product")
fun getProductsWithCategories(): List<ProductWithCategories>

@Transaction
@Query("SELECT * FROM product")
fun getProductsWithReviews(): List<ProductWithReviews>
}

Conclusion

Leveraging Room’s ability to define relationships between different tables opens up a world of possibilities for creating complex yet well-structured databases in Android applications. Whether it’s a one-to-one, one-to-many, or many-to-many relationship, Room’s annotations and features simplify the process of managing and querying interconnected data. This article provided a glimpse into how you can create and utilize these relationships using Kotlin in your Android project. By mastering these concepts, you’ll be better equipped to build apps that efficiently handle and present data to users.

… Thanks for reading …

Clap if this article helps you. If I got something wrong, please comment for improve.
let’s connect on
Linkedin , GitHub

--

--