Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Android – Data Access Object in Room Database

  • Last Updated : 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.

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:

  1. OnConflictStrategy.REPLACE: To replace old data and proceed with the transaction.
  2. OnConflictStrategy.ROLLBACK: To undo a transaction.
  3. OnConflictStrategy.ABORT: To cancel a transaction. The transaction has been reversed.
  4. OnConflictStrategy.FAIL: To fail the transaction. The transaction has been reversed.
  5. 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 fingCourseTakenBy(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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!