【Compose Multiplatform】CMP中使用ROOM開發資料庫 - [KSP2] Annotation value is missing in nested annotations

前言
注意事項 - 在CMP上使用ROOM現階段遇到的兼容問題
  • 注意1. Room版本2.7.0-alpha01之後才支援KMM。

  • 注意2. ksp導入時可能會因為kotlin版本不同而出現版本太低或提示更新版本
    無法Build過
    這時候可以去官方github找有無對應支援的版本 ksp releases

  • 注意3. 使用kotlin搭配ksp會檢查ksp版本跟kotlin相容性
    當使用kotlin 2.0.0 時,gradle sync時顯示版本太低或不相容時
    會出現 Cannot change attributes of configuration ':composeApp:debugFrameworkIosX64' after it has been locked for mutation
    [KSP2] Annotation value is missing in nested annotations

    一開始有搜尋到 KSP2 的問題
    在gradle.property中加入ksp.useKSP2=true可以解決這個問題

    不過雖然上面解決了一個問題後
    可以過gradle sync
    在ksp配置Room又會遇到問題
    例如配置ksp(libs.androidx.room.compiler)
    會一直出現缺少dao [ksp] [MissingType]: xxxxx 'data.xxx.xxxDao' references a type that is not present

    我有去爬文
    有人說可以將kotlin版本降到與ksp相同
    但因為現在用官方Wizard產生CMP已經預設用kotlin 2.0.0
    所以秉持著用新不用舊的原則XD
    如果想在kotlin 2.0.0上成功搭建Room,需要使用workaround去暫解決
    在官方還沒解決的之前可以參考


    我會在這篇的下面提供方法
    大家可以參考看看

    另外我也看到有網友已經提issue給官方了:

實作
導入 - 搭配kotlin版本1.9
  • 步驟1. 導入Room
    • 在.toml文件中加入以下內容:

    • 在build.gradle.kts中加入plugin:

    • 在build.gradle.kts中加入library:

    • 在build.gradle.kts最外層加入以下代碼:

    • 如果使用的kotlin版本大於1.9.20需要在gradle.properties中加入:

導入 - 搭配kotlin版本2.0.0
  • 步驟1. 修改ksp版本:

  • 步驟2. 調整build.gradle.kts:
    • 加入build/generated/ksp/metadata到kotlin block內
    • 用add方法導入ksp
    • 最外層加入tasks.withType
  • 步驟3. 使用workaround實現RoomDatabase

    這個是現階段的workaround
    如果你要用kotlin 2.0.0版本就得先做
    因為現在的兼容性需等待官方修復
實際使用Room
Android Main

實作AppDataBase builder

Koin:

IOS Main

實作AppDataBase builder

Koin:

Common Main

實作AppDataBase

Dao

Entity

參考資料

You might also enjoy