因為之前已經講的很詳細,所以叫 Gemini CLI 開始寫扣後,很簡單就做出想要的功能
@Entity(
    tableName = "notes",
    foreignKeys = [
        ForeignKey(
            entity = CategoryEntity::class,
            parentColumns = ["id"],
            childColumns = ["categoryId"],
            onDelete = ForeignKey.CASCADE
        )
    ]
)
data class NoteEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val title: String,
    val content: String,
    val categoryId: Long,
    val tags: List<String>,
    val createdAt: Long,
    val updatedAt: Long
)
@Entity(tableName = "categories")
data class CategoryEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val name: String,
    val sortOrder: Int
)
@Dao
interface NoteDao {
    @Query("SELECT * FROM notes ORDER BY updatedAt DESC")
    fun getAllNotes(): Flow<List<NoteEntity>>
    @Query("SELECT * FROM notes WHERE id = :id")
    suspend fun getNoteById(id: Long): NoteEntity?
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertNote(note: NoteEntity): Long
    @Update
    suspend fun updateNote(note: NoteEntity)
    @Delete
    suspend fun deleteNote(note: NoteEntity)
}
@Dao
interface CategoryDao {
    @Query("SELECT * FROM categories ORDER BY sortOrder ASC")
    fun getAllCategories(): Flow<List<CategoryEntity>>
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCategory(category: CategoryEntity): Long
    @Update
    suspend fun updateCategory(category: CategoryEntity)
    @Delete
    suspend fun deleteCategory(category: CategoryEntity)
}    
@Database(
    entities = [
        SampleEntity::class  // 範例 Entity,實際專案中可替換為真實 Entity
        // TODO: 在此新增其他 Entity 類別,例如: UserEntity::class, PostEntity::class
    ],
    version = 1,
    exportSchema = false  // 設為 true 並配置 room.schemaLocation 以匯出資料庫架構
)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
    // TODO: 在此新增 DAO
    // 範例:
    // abstract fun userDao(): UserDao
    // abstract fun postDao(): PostDao
    companion object {
        const val DATABASE_NAME = "app_database"
    }
}    
@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    @Provides
    @Singleton
    fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase {
        return Room.databaseBuilder(
            context,
            AppDatabase::class.java,
            "note_app.db"
        ).build()
    }
    @Provides
    fun provideNoteDao(appDatabase: AppDatabase): NoteDao {
        return appDatabase.noteDao()
    }
    @Provides
    fun provideCategoryDao(appDatabase: AppDatabase): CategoryDao {
        return appDatabase.categoryDao()
    }
}