Android - Data Access Object in Room Database - GeeksforGeeks

03 Jan, 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.
Room generates an implementation that inserts all parameters into the database in a single transaction when you annotate a DAO method with @Insert.
Kotlin
@Daointerface 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.
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
@Daointerface CourseDAO {    @Update(onConflict = OnConflictStrategy.REPLACE)    fun updateCourses(vararg courses: Course)      @Update    fun update(courses: Course)}
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
@Daointerface CoursesDao {    @Delete    fun removeCourses(vararg courses: Courses)}
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
@Daointerface CoursesDao {    @Query("SELECT * FROM courses")    fun loadCourses(): Array<Courses>}
Parameters passed to DAO methods can be used in queries written with the @Query annotation.
Kotlin
@Daointerface 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>}
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?)@Daointerface courseDao {    @Query("SELECT first_name, last_name FROM course")    fun loadCourses(): List<CourseTuple>}
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
@Daointerface 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 fingCourseTakenBy(courseName: String): List<Course>}
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.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to View and Locate SQLite Database in Android Studio?
Android Listview in Java with Example
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Image to Drawable Folder in Android Studio?
How to Retrieve Data from the Firebase Realtime Database in Android?
How to Change the Background Color After Clicking the Button in Android?
GridView in Android with Example