Annotation
* Trong file Dao
@Insert(onConflict = OnConflictStrategy.REPLACE) // thêm vào dữ liệu nếu có trùng lặp sẽ thay thế
@Update
@Delete
@Query
* Trong file Database
@Database(
entities = [Article::class],
version = 1
)
@TypeConverters(Converters::class)
abstract class ArticleDatabase : RoomDatabase() {
abstract fun getArticleDao(): ArticleDao
companion object{
@Volatile
private var instance: ArticleDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context) = instance ?: synchronized(LOCK){
instance ?: createDatabase(context).also { instance = it }
}
private fun createDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
ArticleDatabase::class.java,
"article_db.db"
).build()
}
}
*File Converter (do Room chỉ lưu trữ những kiểu dữ liệu nguyên thuỷ nên nếu muốn lưu kiểu dữ liệu custom thì cần có file này)
class Converters {
@TypeConverter
fun fromSource(source: Source) : String {
return source.name
}
@TypeConverter
fun toSource(name: String) : Source {
return Source(name, name)
}
}
Khuôn mẫu sẽ như này, Đều cần phải khai báo 2 Annotation, đồng thời phải báo Annotation ở file database đã code bên trên
- Hàm đầu tiên trả về kiểu dữ liệu room hỗ trợ, hàm thứ 2 trả về kiểu dữ liệu custom
Nhận xét
Đăng nhận xét