如何在Android中使用Room Persistence ORM工具实现created_at和Updated_at列 [英] How to implement created_at and updated_at column using Room Persistence ORM tools in android

查看:103
本文介绍了如何在Android中使用Room Persistence ORM工具实现created_at和Updated_at列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Android中使用Room Persistence ORM工具实现created_atupdated_at列,当创建或更新表中的行时可以自动更新时间戳?

How can I implement created_at and updated_at columns using Room Persistence ORM tools in Android, that can update the timestamp automatically when creating or updating a row in a table?

推荐答案

我研究了许多站点,但仍未发现当我们QueryInsert时,任何结果都可以处理middleware或类似callbacks的结果. ,UpdateDelete,...来自DAO s的方法.

I've research many sites, but still not found any results can handle middleware or something like callbacks when we Query, Insert, Update, or Delete,... methods from DAOs.

正如@selvin所说,RoomDatabase.Callback接口仅在首次创建数据库时调用.因此,使用该接口是错误的方式. 因此,以下方法可能对我来说是个窍门,希望这对您有所帮助:

As @selvin said, RoomDatabase.Callback interface only call when database created in first time. So, use that interface is incorrect way. So, may be the way below is a trick for me, hope this will help you:

此模型可确保数据库中的所有模型始终在creation_datemodification_date列中可用.

This model to sure that all models in database always available columns creation_date and modification_date.

abstract class BaseModel: Serializable {

    @PrimaryKey(autoGenerate = true) 
    @Expose
    var id: Long = 0

    @ColumnInfo(name = "description")
    @SerializedName(value = "description")
    var description: String? = null

    @ColumnInfo(name = "creation_date")
    @SerializedName(value = "creation_date")
    var creationDate: Date = Date(System.currentTimeMillis())

    @ColumnInfo(name = "modification_date")
    @SerializedName(value = "modification_date")
    var modificationDate: Date = Date(System.currentTimeMillis())

}

2.创建一个BaseDAO

BaseDAO内,我还创建了一个名为DAOWrapper的包装器类,该类将存储所有有用的方法,在将模型数据与DAO交互之前,我们将使用这些方法来处理诸如中间件"之类的数据.

2. Create an BaseDAO

Inside BaseDAO, I also create a wrapper class named DAOWrapper, this class will store all helpful methods that we will use to process data like "middleware" before interact model's data to DAO.

那么,为什么我们不在BaseDAO内部创建方法? ->我们不能那样做!使用这种方式将与android体系结构发生冲突,而且编译器也会出错(在DAO对象中声明的所有方法都需要注释UpdateQuery,...).

So, why we don't create methods inside BaseDAO? -> We cannot do that! use that way will conflict android architecture and also we will have error from compiler (all methods declared in DAO object requires annotation Update, Query,...).

interface BaseDAO<T> where T: BaseModel {

    fun getAll(): List<T>

    @Insert(onConflict = OnConflictStrategy.ABORT)
    fun insert(modelData: T)

    @Update(onConflict = OnConflictStrategy.ABORT)
    fun update(modelData: T)

    companion object {

        open class DAOWrapper<P, T>(private val daoInstance: T) where T: BaseDAO<P>, P: BaseModel {

            fun insertWithTimestapData(modelData: P) {
                modelData.modificationDate = Date(System.currentTimeMillis())
                this@DAOWrapper.daoInstance.insert(modelData)
            }

        }

    }

}

3.要使用DAOWrapper

val appDatabase = // Do something to get RoomDatabase instance...
val exampleDao = appDatabase.exampleDAO()
val exampleDaoWrapper = BaseDAO.Companion.DAOWrapper(exampleDao)

val exampleModel = ExampleModel(name = "Example Name")
exampleDaoWrapper.insertWithTimestapData(exampleModel)

参考文献

下面是RoomDatabase的示例实例和我在上面的代码中使用的示例模型:

References

Below is example instance of RoomDatabase and example model I used in code above:

/** ExampleModel.kt */
@Entity(
    tableName = "examples",
    indices = [Index(value = arrayOf("name"), unique = true)]
)
class ExampleModel(): BaseModel() {

    @ColumnInfo(name = "name")
    @SerializedName(value = "name")
    var name: String = String()

    @Ignore
    constructor(name: String): this() {
        this@ExampleModel.name = name
    }

}


/** ExampleDAO.kt */
@Dao
interface ExampleDAO: BaseDAO<ExampleModel> {

    @Query("SELECT * FROM `examples`")
    override fun getAll(): List<ExampleModel>

}


/** AppDatabase.kt **/
@Database(entities = [ExampleModel::class], version = 1)
abstract class AppDatabase: RoomDatabase() {

    abstract fun exampleDAO(): ExampleDAO

    companion object {
        private var databaseInstance: AppDatabase? = null
        public const val DatabaseName: String = "app_database"

        fun getDatabase(context: Context): AppDatabase {
            this@Companion.destroyAndCreateNewInstanceIfNeeded(context)
            return this@Companion.databaseInstance!!
        }

        fun destroyAndCreateNewInstanceIfNeeded(context: Context) {
            synchronized(AppDatabase::class) {
                this@Companion.databaseInstance?.close()
                this@Companion.databaseInstance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    this@Companion.DatabaseName
                ).build()
            }
        }
    }

}

这篇关于如何在Android中使用Room Persistence ORM工具实现created_at和Updated_at列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆