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.

interfaceBaseDao<T> {

/**
 * Insert an object in the database.
 *
 * @param obj the object to be inserted.
 */@Insertfuninsert(obj: T)/**
 * Insert an array of objects in the database.
 *
 * @param obj the objects to be inserted.
 */@Insertfuninsert(vararg obj: T)/**
 * Update an object from the database.
 *
 * @param obj the object to be updated
 */@Updatefunupdate(obj: T)/**
 * Delete an object from the database
 *
 * @param obj the object to be deleted
 */@Deletefundelete(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
 */@DaointerfaceBaseDao<T> {

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

    // update List@Updatesuspendfunupdate(obj: List<T>?): Int

}

@DaointerfaceMyObjectDao : BaseDao<MyObject> {

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

}

Can then be called like:

valids= MyObjectDao.insert(objectList)

Post a Comment for "Android Room Generic Dao"