You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为IntelliJ内置向导创建的Compose Desktop应用添加Room库?

为IntelliJ内置向导创建的Compose Desktop项目配置Room库

1. 修改build.gradle.kts配置

1.1 新增KAPT插件

Room的注解处理依赖KAPT,在plugins块中添加:

plugins {
    kotlin("jvm")
    id("org.jetbrains.compose")
    id("org.jetbrains.kotlin.plugin.compose")
    kotlin("kapt") // 新增:Room注解处理所需插件
}

1.2 添加Room及SQLite依赖

在dependencies块中加入Room核心库、KTX扩展、注解处理器,以及JVM环境必需的SQLite驱动:

dependencies {
    implementation(compose.desktop.currentOs)
    
    // Room依赖(可替换为最新稳定版)
    val roomVersion = "2.6.1"
    implementation("androidx.room:room-runtime:$roomVersion")
    implementation("androidx.room:room-ktx:$roomVersion")
    kapt("androidx.room:room-compiler:$roomVersion")
    // JVM环境必须的SQLite驱动
    implementation("org.xerial:sqlite-jdbc:3.45.1.0")
}

1.3 仓库配置确认

你的repositories已经包含google()和mavenCentral(),满足依赖下载需求,无需额外修改。

2. 创建Room核心组件

2.1 定义实体类

示例创建一个Note实体,对应数据库表:

import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity(tableName = "notes")
data class Note(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val title: String,
    val content: String
)

2.2 编写Dao接口

定义数据库操作方法:

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow

@Dao
interface NoteDao {
    @Insert
    suspend fun insertNote(note: Note)

    @Query("SELECT * FROM notes")
    fun getAllNotes(): Flow<List<Note>>
}

2.3 创建数据库实例类

构建Room数据库并提供全局访问入口:

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import java.io.File

@Database(entities = [Note::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun noteDao(): NoteDao

    companion object {
        // 数据库文件存储在用户主目录下,可自行调整路径
        fun getInstance(): AppDatabase {
            val dbFile = File(System.getProperty("user.home"), "compose-desktop-room.db")
            return Room.databaseBuilder(
                context = dbFile.parentFile,
                klass = AppDatabase::class.java,
                name = dbFile.name
            ).build()
        }
    }
}

3. 在Compose Desktop应用中集成Room

在Main.kt中初始化数据库,并在UI中调用数据库操作:

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

fun main() = application {
    val db = AppDatabase.getInstance()
    val noteDao = db.noteDao()

    Window(onCloseRequest = ::exitApplication) {
        RoomDemoUI(noteDao = noteDao)
    }
}

@Composable
fun RoomDemoUI(noteDao: NoteDao) {
    val notes by noteDao.getAllNotes().collectAsState(initial = emptyList())

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = {
            // 数据库操作必须在非UI线程执行
            kotlinx.coroutines.GlobalScope.launch(Dispatchers.IO) {
                noteDao.insertNote(Note(title = "测试标题", content = "测试内容"))
            }
        }) {
            Text(text = "添加笔记")
        }

        Text(text = "当前笔记数量:${notes.size}")
        notes.forEach { note ->
            Text(text = "${note.title}: ${note.content}")
        }
    }
}

关键注意点

  • 所有数据库操作必须放在非UI线程,示例中使用Dispatchers.IO调度器
  • 可根据需求修改数据库文件的存储路径
  • 定期检查Room和SQLite驱动的版本,替换为最新稳定版

内容的提问来源于stack exchange,提问作者Abdo21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:06:06