Discover how these classes turn messy data into a clean, easy-to-use system!
Why Entity, DAO, Database classes in Android Kotlin? - Purpose & Use Cases
Imagine you want to save a list of your favorite books on your phone. You try to write all the data directly into files or remember it in your app without any structure.
Every time you want to add, find, or change a book, you have to search through messy data manually.
Doing this by hand is slow and confusing. You might lose data or make mistakes because there is no clear way to organize or find your books.
It's like having a messy desk where you keep all your papers scattered and have to dig through them every time.
Using Entity, DAO, and Database classes gives you a neat system to store and manage your data.
Entities represent your data items (like a book), DAOs are the helpers that know how to save and get data, and the Database class ties everything together safely and efficiently.
fun saveBook(title: String, author: String) {
// Write to file manually
}@Entity data class Book(@PrimaryKey(autoGenerate = true) val id: Int = 0, val title: String, val author: String) @Dao interface BookDao { @Insert fun insert(book: Book) } @Database(entities = [Book::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun bookDao(): BookDao }
This system lets you easily add, find, update, and delete data without worrying about messy details.
Think of a recipe app where you save your favorite recipes. Entities store each recipe, DAOs help you search or add new ones, and the Database keeps everything organized and safe.
Entities define what data looks like.
DAOs handle how to access and change data.
Database classes connect everything for smooth data management.
Practice
Entity class in Android Room?Solution
Step 1: Understand the role of Entity
An Entity class represents a table in the database by defining its columns and data types.Step 2: Differentiate from DAO and Database
DAO provides query methods, and Database manages connections, so they are not the main purpose of Entity.Final Answer:
To define the structure of a database table -> Option AQuick Check:
Entity = Table structure [OK]
- Confusing Entity with DAO
- Thinking Entity manages database connections
- Assuming Entity handles UI
id?Solution
Step 1: Identify correct primary key annotation
The primary key must be annotated with@PrimaryKeyon the property inside the data class.Step 2: Check syntax correctness
@Entity data class User(@PrimaryKey val id: Int, val name: String) correctly places@PrimaryKeybefore theidproperty in a data class annotated with@Entity.Final Answer:
@Entity data class User(@PrimaryKey val id: Int, val name: String) -> Option AQuick Check:
Primary key uses @PrimaryKey annotation [OK]
- Placing @PrimaryKey after property name
- Using primaryKeys parameter incorrectly
- Missing @PrimaryKey annotation
getAllUsers() when called?
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAllUsers(): List<User>
}Solution
Step 1: Analyze the DAO method signature
The methodgetAllUsers()returnsList<User>, which means a list of User objects.Step 2: Understand Room query return types
Since the return type is explicitlyList<User>, it returns a list, not a single object or LiveData.Final Answer:
A list of User objects -> Option CQuick Check:
Return type List<User> means list of users [OK]
- Confusing List<User> with LiveData
- Expecting a single User instead of list
- Thinking Room returns Cursor by default
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
fun getInstance(context: Context): AppDatabase {
return Room.databaseBuilder(context, AppDatabase::class.java, "app_db").build()
}
}
}Solution
Step 1: Review database class structure
The database class is abstract and correctly annotated with @Database and version number.Step 2: Check instance creation method
ThegetInstancemethod creates a new database instance every time, lacking a singleton pattern to reuse one instance.Final Answer:
No singleton pattern to prevent multiple database instances -> Option BQuick Check:
Database instance should be singleton [OK]
- Not using singleton for database instance
- Confusing abstract class with interface
- Ignoring @Entity annotation on User
User and Book. You also want to provide DAOs for both. Which is the correct way to define the database class?Solution
Step 1: Check entities list in @Database annotation
Both User and Book entities must be included in the entities array.Step 2: Verify class declaration and DAO methods
The database class must be abstract and extend RoomDatabase, with abstract DAO methods.Final Answer:
@Database(entities = [User::class, Book::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun bookDao(): BookDao } -> Option DQuick Check:
Entities list and abstract class with DAO methods [OK]
- Omitting one entity from entities list
- Not extending RoomDatabase
- Making database class non-abstract
Ready to prove it?
Pass the test and this pattern moves unknown
