如何在 android 中使用 Room Persistence ORM 工具实现created_at和updated_at列
如何使用 Android 中的工具实现和列,以便在创建或更新表中的行时自动更新时间戳?created_at
updated_at
Room Persistence ORM
如何使用 Android 中的工具实现和列,以便在创建或更新表中的行时自动更新时间戳?created_at
updated_at
Room Persistence ORM
我研究过许多网站,但仍然没有发现任何结果可以处理,或者当我们,,,或,...来自 s 的方法。middleware
callbacks
Query
Insert
Update
Delete
DAO
正如@selvin所说,接口仅在首次创建数据库时调用。因此,使用该界面是不正确的方式。所以,可能是下面的方式对我来说是一个技巧,希望这对你有所帮助:RoomDatabase.Callback
BaseModel
此模型可确保数据库中的所有模型始终可用列和 。creation_date
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())
}
BaseDAO
在里面,我还创建了一个名为 的包装类,这个类将存储所有有用的方法,我们将使用这些方法来处理数据,如“中间件”,然后再将模型的数据与DAO进行交互。BaseDAO
DAOWrapper
那么,为什么我们不在BaseDAO
中创建方法呢?-> 我们不能那样做!使用这种方式将冲突Android架构,并且我们还会遇到编译器的错误(DAO对象中声明的所有方法都需要注释,,...)。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)
}
}
}
}
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 和示例模型的示例实例:
/** 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()
}
}
}
}
下面用一个 Java 示例来跟进上述内容。
所有文件室实体的基本实体这将映射到包含 id、created_at和updated_at列的表。
public abstract class BaseEntity implements Serializable {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "created_at", defaultValue = "CURRENT_TIMESTAMP")
@TypeConverters(DateConverter.class)
private Date createdAt;
@ColumnInfo(name = "updated_at", defaultValue = "CURRENT_TIMESTAMP")
@TypeConverters(DateConverter.class)
private Date updatedAt;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
}
房间日期类型转换器这会将 Java 日期转换为可以保存在 sqlite 数据库中的数字。
public class DateConverter {
@TypeConverter
public static Date toDate(Long timestamp) {
if (timestamp == null) {
return null;
}
return new Date(timestamp);
}
@TypeConverter
public static Long toTimestamp(Date date) {
if (date == null) {
return null;
}
return date.getTime();
}
}
抽象的巴塞道此 Dao 实现了所有基本的插入、更新和删除方法。
@Dao
public abstract class AbstractBaseEntityDao<T extends BaseEntity> {
@Insert
public abstract long actualInsert(T t);
public long insert(T t) {
t.setCreatedAt(new Date());
t.setUpdatedAt(new Date());
return actualInsert(t);
}
@Insert
public abstract List<Long> actualInsertAll(List<T> ts);
public List<Long> insertAll(List<T> ts) {
if (ts != null) {
for (T t : ts) {
t.setCreatedAt(new Date());
t.setUpdatedAt(new Date());
}
}
return actualInsertAll(ts);
}
@Update
public abstract void actualUpdate(T t);
public void update(T t) {
t.setUpdatedAt(new Date());
actualUpdate(t);
}
@Update
public abstract void actualUpdateAll(List<T> ts);
public void updateAll(List<T> ts) {
if (ts != null) {
for (T t : ts) {
t.setUpdatedAt(new Date());
}
}
actualUpdateAll(ts);
}
@Delete
public abstract void delete(T t);
@Delete
public abstract void deleteAll(List<T> ts);
}
用户和用户道下面是用户的具体实体和 Dao 的示例(典型用例)。
@Entity(tableName = "users")
public class User extends BaseEntity {
@ColumnInfo(name = "name")
private String name;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Dao
public abstract class UserDao extends AbstractBaseEntityDao<User> {
@Query("select * from users")
public abstract List<User> getAllUsers();
}
如何插入用户这将使用抽象基础EntityDao,它设置created_at和updated_at时间戳。
注意:不要在UI线程上执行此操作!!
YourDatabase database = YourDatabase.getInstance(getApplicationContext());
UserDao userDao = database.userDao();
long userId = userDao.insert(userToAdd);
userToAdd.setId(userId);
如何更新用户
YourDatabase database = YourDatabase.getInstance(getApplicationContext());
UserDao userDao = database.userDao();
userDao.update(userToEdit);