Skip to content Skip to sidebar Skip to footer

Android Room Generic DAO

Good day Stack, i'm working on an Android project that uses Android's Room 1.0.0 Alpha 5, the main issue that i'm facing is that every time i need to call one of the DAO from room

Solution 1:

You can use inheritance and create a BaseDao which will be implemented by all your child Dao. This way you won't need to write the common methods again and again.

interface BaseDao<T> {

/**
 * Insert an object in the database.
 *
 * @param obj the object to be inserted.
 */
@Insert
fun insert(obj: T)

/**
 * Insert an array of objects in the database.
 *
 * @param obj the objects to be inserted.
 */
@Insert
fun insert(vararg obj: T)

/**
 * Update an object from the database.
 *
 * @param obj the object to be updated
 */
@Update
fun update(obj: T)

/**
 * Delete an object from the database
 *
 * @param obj the object to be deleted
 */
@Delete
fun delete(obj: T)
}

Read more about it: https://gist.github.com/florina-muntenescu/1c78858f286d196d545c038a71a3e864#file-basedao-kt

Original credits to Florina.


Solution 2:

I played around a bit with the answer of Akshay Chordiya, but needed two additions:

  • ability to insert/update List
  • return values to monitor insert/update success

Here is what I came up with:

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Update

/**
 * List of all generic DB actions
 * All use suspend to force kotlin coroutine usage, remove if not required
 */
@Dao
interface BaseDao<T> {

    // insert single
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(obj: T?): Long

    // insert List
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(obj: List<T>?) : List<Long>

    // update List
    @Update
    suspend fun update(obj: List<T>?): Int

}

@Dao
interface MyObjectDao : BaseDao<MyObject> {

    @Query("SELECT * from $TABLE_NAME WHERE $COL_ID = :id")
    suspend fun getById(id: Long): MyObject

}

Can then be called like:

val ids = MyObjectDao.insert(objectList)

Post a Comment for "Android Room Generic DAO"