如何在Android中使用Room Persistence ORM工具实现created_at和Updated_at列 [英] How to implement created_at and updated_at column using Room Persistence ORM tools in android
问题描述
如何在Android中使用Room Persistence ORM
工具实现created_at
和updated_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?
推荐答案
我研究了许多站点,但仍未发现当我们Query
,Insert
时,任何结果都可以处理middleware
或类似callbacks
的结果. ,Update
或Delete
,...来自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 DAO
s.
正如@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_date
和modification_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对象中声明的所有方法都需要注释Update
,Query
,...).
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屋!