Android – Data Access Object in Room Database
Last Updated :
14 Sep, 2022
Data Access Objects, or DAOs, are used in Room to access your application’s persisted data. When compared to query builders or direct queries, they are a better and more modular way to access your database. You should also make a note that a DAO need not be only a class. If it’s an abstract class, it can have a function Object() { [native code] } that only accepts a RoomDatabase as a parameter. At compile time, Room creates each DAO implementation. DAO allows you to perform a variety of operations such as inserting, updating, deleting, and running raw queries. You can also easily incorporate LiveData, RxJava Observables, and Kotlin Coroutines into DAOs.
Insertion
Room generates an implementation that inserts all parameters into the database in a single transaction when you annotate a DAO method with @Insert.
Kotlin
@Dao
interface gfgDao {
@Insert (onConflict = OnConflictStrategy.REPLACE)
fun insertCourses(vararg course: Course) @Insert
fun insertAndroid(course1: Course, course2: Course)
@Insert
fun insertDataStructures(course: Course, prices: List<Course>)
}
|
The onConflict annotation parameter indicates what to do if a conflict occurs during insertion. It can be any of the following values:
- OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction.
- OnConflictStrategy.ROLLBACK: To undo a transaction.
- OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed.
- OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed.
- OnConflictStrategy.NONE: To disregard the conflict.
Note: ROLLBACK and FAIL strategies are no longer supported. Instead, use ABORT.
Kotlin
@Dao
interface CourseDAO {
@Update (onConflict = OnConflictStrategy.REPLACE)
fun updateCourses(vararg courses: Course)
@Update
fun update(courses: Course)
}
|
Deletion
When you create a DAO method and annotate it with @Delete, Room generates an implementation that deletes a set of entities from the database, as specified by the parameters. It searches for entities to delete using the primary keys.
Kotlin
@Dao
interface CoursesDao {
@Delete
fun removeCourses(vararg courses: Courses)
}
|
Simple questions
The main annotation used in DAO classes is @Query. It enables you to read and write data from a database. Because each @Query method is validated at compile-time, if there is a problem with the query, a compilation error occurs rather than a runtime failure. Room also verifies the query’s return value, so that if the name of a field in the returned object does not match the corresponding column names in the query response, Room notifies you in one of two ways: It issues a warning if only a subset of the field names matches. If no field names match, it returns an error.
Kotlin
@Dao
interface CoursesDao {
@Query ( "SELECT * FROM courses" )
fun loadCourses(): Array<Courses>
}
|
Including parameters in the query
Parameters passed to DAO methods can be used in queries written with the @Query annotation.
Kotlin
@Dao
interface CoursesDao {
@Query ( "SELECT * FROM courses WHERE price BETWEEN :minPrice AND :maxPrice" )
fun loadAllCourses(minPrices: Int, maxPrices: Int): Array<Course>
@Query ( "SELECT * FROM courses WHERE first_course LIKE :search " +
"OR last_course LIKE :search" )
fun findCourses(search: String): List<Courses>
}
|
Column subsets are returned
In-Room, you can also return subsets of columns from a query.
Kotlin
data class coursesTuple(
@CourseName (name = "first_course" ) val first_course: String?,
@CourseName (name = "last_course" ) val last_course: String?
) @Dao
interface courseDao {
@Query ( "SELECT first_name, last_name FROM course" )
fun loadCourses(): List<CourseTuple>
}
|
Multiple table queries
Some of your queries may necessitate access to multiple tables in order to calculate the result. Room allows you to write any query, including table joins. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room looks for invalidation in all tables referenced in the query.
Kotlin
@Dao
interface UserDAO {
@Query (
"SELECT * FROM users " +
"INNER JOIN loan ON loan.book_id = course.id " +
"INNER JOIN user ON user.id = loan.course " +
"WHERE course.name LIKE :courseName"
)
fun findCourseTakenBy(courseName: String): List<Course>
}
|
Types of query returns
The room supports a wide range of query method return types, including specialized return types for interoperability with specific frameworks or APIs. Query methods can return LiveData, Observable, and Flow objects. You can also create a DAO method suspend function. Separate articles are dedicated to each of these topics.
Similar Reads
How to Add Data to Back4App Database in Android?
Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
4 min read
How to Access Data or Data Folder in an Android Device?
Android Operating System offers several storage methods to save your app data and images, audio files, docs, etc. App-specific storage: It only stores the data that is used by your App.Shared Storage: It stores files including images and documents.Databases: It provides a local Database for your app
7 min read
How to Install and Add Data to Realm Database in Android?
Realm Database is a service which is provided by MongoDb which is used to store data in users device locally. With the help of this data can be stored easily in users' devices and can be accessed easily. We can use this database to store data in the user's device itself. This is a series of 4 articl
8 min read
Room Database with Kotlin Coroutines in Android
This project will be used for the implementation phase. If you have not yet completed the project, you should do so and then return. To keep things simple, the project employs a basic MVVM architecture. The complete code for the implementation mentioned in this blog can be found in the project itsel
3 min read
How to Read Data from SQLite Database in Android?
In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in RecyclerView. What we are going to
12 min read
How to Access SQLite Database in Android For Debugging?
A software library that provides a relational database management system is called SQLite. It allows the users to interact with RDBMS. The lite in SQLite denotes the lightweight when it comes to setup, database administration, and resources required. In SQLite, a database is stored in a single file
10 min read
How to Prepopulate Room Database in Android?
Room is one of the Jetpack Architecture Components in Android. This provides an abstract layer over the SQLite Database to save and perform the operations on persistent data locally. This is recommended by Google over SQLite Database although the SQLite APIs are more powerful they are fairly low-lev
3 min read
How to Create and Add Data to SQLite Database in Android?
SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required. In this article, we will take a look at creating an SQLite database in the Android app and adding data to that database in the Android app. This is a series of 4 ar
8 min read
Android SearchView in Room Database
SearchView in databases is a pretty basic functionality that you can see in most of the applications in your day-to-day life, then why not, you should learn and implement it. it is not too much complicated to implement in your application. There are a lot of easier ways that are how you can implemen
12 min read
How to Delete Data in SQLite Database in Android?
In the previous articles, we have seen three operations of CRUD operations such as create, read and update operations in our Android app. In this article, we will take a look at adding delete operation for deleting our items stored in the SQLite database. What we are going to build in this article?
8 min read