You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.5 KiB
57 lines
1.5 KiB
package com.example.myapplication.data
|
|
|
|
import android.content.Context
|
|
import androidx.room.Database
|
|
import androidx.room.Room
|
|
import androidx.room.RoomDatabase
|
|
|
|
/**
|
|
* 便签数据库类
|
|
*
|
|
* 使用 Room 持久化库管理 SQLite 数据库
|
|
* 采用单例模式确保整个应用只有一个数据库实例
|
|
*
|
|
* @property noteDao 提供便签数据访问对象
|
|
*/
|
|
@Database(
|
|
entities = [Note::class],
|
|
version = 1,
|
|
exportSchema = false
|
|
)
|
|
abstract class NoteDatabase : RoomDatabase() {
|
|
|
|
/**
|
|
* 获取便签数据访问对象
|
|
*
|
|
* @return NoteDao 实例,用于执行数据库操作
|
|
*/
|
|
abstract fun noteDao(): NoteDao
|
|
|
|
companion object {
|
|
@Volatile
|
|
private var INSTANCE: NoteDatabase? = null
|
|
|
|
/**
|
|
* 获取数据库单例实例
|
|
*
|
|
* 使用双重检查锁定模式确保线程安全
|
|
*
|
|
* @param context 应用上下文
|
|
* @return NoteDatabase 单例实例
|
|
*/
|
|
fun getDatabase(context: Context): NoteDatabase {
|
|
return INSTANCE ?: synchronized(this) {
|
|
val instance = Room.databaseBuilder(
|
|
context.applicationContext,
|
|
NoteDatabase::class.java,
|
|
"note_database"
|
|
)
|
|
.fallbackToDestructiveMigration() // 数据库版本变化时销毁重建
|
|
.build()
|
|
INSTANCE = instance
|
|
instance
|
|
}
|
|
}
|
|
}
|
|
}
|