[
{
"name" : "phase1",
"type" : "purchase",
"submenu": [
{
"name": "insert",
"route": "insert"
},
{
"name": "send",
"route": "send"
},
{
"name": "delete",
"route": "delete"
}
]
},
{
"name" : "phase2",
"type" : "refund",
"submenu": [
{
"name": "insert",
"route": "insert"
},
{
"name": "send",
"route": "send"
},
{
"name": "delete",
"route": "delete"
}
]
}
]
我將使用以下組件讀取 json 并將其放入 Room 資料庫。所以我嘗試創建并插入 MenuEntity 和 SubMenu,
選單物體
@Entity(tableName = "menus", primaryKeys = ["name", "type"])
data class MenuEntity(
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "type")
val type: String,
@Embedded
val submenus: List<Submenu>,
)
子選單
data class Submenu(
@ColumnInfo(name = "submenu_name")
val name: String,
@ColumnInfo(name = "route")
val route: String
)
選單
data class Menu(
val name: String,
val type: String,
val submenus: List<Submenu>,
)
但發生了以下錯誤。
Entities and POJOs must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type). - java.util.List
我想讀取 json 檔案 -> 插入資料庫 -> 從資料庫中讀取
我想問你如何制作物體。
uj5u.com熱心網友回復:
您的問題是您不能將串列/陣列型別作為列。列必須是一組有限的型別 String、Integer、Long、Double、Float、ByteArray 是最常見的可接受型別。
所以
@Embedded
val submenus: List<Submenu>
不會起作用,我相信這就是您收到錯誤的原因(Room 不知道如何處理串列)。
您可以選擇兩條路線:-
- 利用關系,從而為子選單串列使用第二個表(物體)。
- 創建和存盤子選單的表示,可能作為字串(json)。在這種情況下,您將提取子選單的 json 并存盤它。
這是 1 的作業示例
似乎最接近的一個選項是使用具有一對多關系的兩個表。即一個 Menu 可以有 0-n 個子選單。為了建立關系,您在子選單中有一個附加列,用于唯一標識子選單所屬的選單。
Menu 和 Submenu 類保持不變。
選單物體是:-
@Entity(tableName = "menus", indices = [Index("name", "type", unique = true)])
data class MenuEntity(
@PrimaryKey
@ColumnInfo(name = "menu_id")
val menuId: Long? = null,
@ColumnInfo(name = "name")
val name: String,
@ColumnInfo(name = "type")
val type: String
)
- 子選單串列已被洗掉
- 添加了一個額外的(但不是真的)列
- 因為列定義將是
menu_id INTEGER PRIMARY KEY然后它是通常隱藏的 rowid 列的別名,該列存在于所有表中(除了 Room 當前不允許的 WITHOUT ROWID 表)。 - 所以添加此列沒有開銷。但是,rowid 的處理效率更高,速度可以提高兩倍,因此效率可能會提高。
- 因為列定義將是
- 額外的列簡化了 Menu 和 Submenu 之間的關系,使用簡單鍵而不是復合鍵。
子選單表SubmenuEntity 的新類
@Entity(tableName = "submenus",
/* Optional but useful as referential integrity is enforced */
foreignKeys = [
ForeignKey(
entity = MenuEntity::class,
parentColumns = ["menu_id"],
childColumns = ["menu_id_map"],
/* Optional within A Foreign Key */
onDelete = CASCADE,
onUpdate = CASCADE
)
]
)
data class SubmenuEntity(
@PrimaryKey
@ColumnInfo(name = "submenu_id")
val id: Long? = null,
@Embedded
val submenu: Submenu,
@ColumnInfo(name = "menu_id_map")
val menuMapId: Long
) {
// Bonus function that will get a Submenu from a SubmenuEntity
fun getSubmenuFromSubmenuEntity(submenuEntity: SubmenuEntity): Submenu {
return Submenu(name = submenuEntity.submenu.name, route = submenuEntity.submenu.route)
}
}
注意已經嵌入了Submenu類
這基本上是一個帶有 2 個附加列的子選單
- submenu_id 列是 rowid 的別名,如前所述,以及
- 用于存盤父選單的 menu_id 的列,即關系
為了完整起見,添加了外鍵約束。這減少了子選單沒有父選單從而成為孤兒的機會。根據評論,不需要約束。
To all retrieval of Menus with the SubMenus via the realtionship then you have a POJO that embeds the parent (menu) with the @Embedded annotation and has a list of the children annotated with @Relation e.g. :-
data class MenuWithSubmenus (
@Embedded
val menuEntity: MenuEntity,
@Relation(
entity = SubmenuEntity::class,
parentColumn = "menu_id",
entityColumn = "menu_id_map")
val submenuList: List<SubmenuEntity>
)
You then want the means of accessing the database, these are Dao's and you have either an interface or an abstract class annotated with @Dao such as
@Dao
abstract class AllDao {
@Insert
abstract fun insert(menuEntity: MenuEntity): Long
@Insert
abstract fun insert(submenu: SubmenuEntity): Long
@Transaction
@Query("SELECT * FROM menus")
abstract fun getALlMenusWithSubmenus(): List<MenuWithSubmenus>
}
It is all put together via an abstract class annotated with @Database where the entities are defined and an abstract function is defined to get the class(es) annotated with @Dao. Often a method will be included that caters for getting a single instance of the Database class. So you could have :-
@Database(entities = [MenuEntity::class, SubmenuEntity::class],version = 1)
abstract class TheDatabase: RoomDatabase() {
abstract fun getAllDao(): AllDao
companion object {
private var instance: TheDatabase? = null
fun getInstance(context: Context) : TheDatabase {
if (instance == null) {
instance = Room.databaseBuilder(
context,
TheDatabase::class.java,
"menu_database.db"
)
.allowMainThreadQueries() // Used for convenience/brevity
.build()
}
return instance as TheDatabase
}
}
}
- Note for brevity and convenience
.allowMainThreadQuerieshas been used to allow the demo to run on the main thread and thus not have all the extra code to handle running off the main thread. The latter being recommended for Apps that are to be distributed.
Finally an Activity MainActivity to demonstrate the above.
class MainActivity : AppCompatActivity() {
lateinit var db: TheDatabase
lateinit var dao: AllDao
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
db = TheDatabase.getInstance(this)
dao = db.getAllDao();
// Get the JSON and add the Menu's and Submenu's to the database.
Log.d("DBINFO",getTheJsonInputString()) // Write the JSON to the log
val menuList = Gson().fromJson(getTheJsonInputString(), Array<Menu>::class.java)
for (m: Menu in menuList) {
var menuId = dao.insert(MenuEntity(name = m.name, type = m.type))
for (sm: Submenu in m.submenus) {
dao.insert(SubmenuEntity(submenu = Submenu(sm.name,sm.route),menuMapId = menuId))
}
}
// extract the data from the database as MenuWithSubmenus objects
for (mws: MenuWithSubmenus in dao.getALlMenusWithSubmenus()) {
Log.d("DBINFO"," Menu is ${mws.menuEntity.name} Type is ${mws.menuEntity.type} ID is ${mws.menuEntity.menuId}")
for(sm: SubmenuEntity in mws.submenuList) {
var currentSubmenu = sm.getSubmenuFromSubmenuEntity(sm) // Check the function works
Log.d("DBINFO","\tSubmenu is ${sm.submenu.name} Route is ${sm.submenu.route} ID is ${sm.id} Parent Menu is ${sm.menuMapId}")
Log.d("DBINFO", "\tSubmenu extract from SubmenuEntity is ${currentSubmenu.name} Route is ${currentSubmenu.route}")
}
}
}
/**
* generate some test data
*/
private fun getTheJsonInputString(): String {
val menulist: List<Menu> = listOf(
Menu("menu1","type1",
listOf(
Submenu(name = "SM1", route = "route1"),
Submenu(name = "SM2", route = "route2"),
Submenu(name = "SM3", route = "route3")
)
),
Menu( name = "menu2", type = "type2",
listOf(
Submenu(name = "SM4", route = "route4"),
Submenu(name = "SM5", route = "route5")
)
)
)
return Gson().toJson(menulist)
}
}
The above is designed to only run once. When run then the following is output to the log:-
D/DBINFO: [{"name":"menu1","submenus":[{"name":"SM1","route":"route1"},{"name":"SM2","route":"route2"},{"name":"SM3","route":"route3"}],"type":"type1"},{"name":"menu2","submenus":[{"name":"SM4","route":"route4"},{"name":"SM5","route":"route5"}],"type":"type2"}]
D/DBINFO: Menu is menu1 Type is type1 ID is 1
D/DBINFO: Submenu is SM1 Route is route1 ID is 1 Parent Menu is 1
D/DBINFO: Submenu extract from SubmenuEntity is SM1 Route is route1
D/DBINFO: Submenu is SM2 Route is route2 ID is 2 Parent Menu is 1
D/DBINFO: Submenu extract from SubmenuEntity is SM2 Route is route2
D/DBINFO: Submenu is SM3 Route is route3 ID is 3 Parent Menu is 1
D/DBINFO: Submenu extract from SubmenuEntity is SM3 Route is route3
D/DBINFO: Menu is menu2 Type is type2 ID is 2
D/DBINFO: Submenu is SM4 Route is route4 ID is 4 Parent Menu is 2
D/DBINFO: Submenu extract from SubmenuEntity is SM4 Route is route4
D/DBINFO: Submenu is SM5 Route is route5 ID is 5 Parent Menu is 2
D/DBINFO: Submenu extract from SubmenuEntity is SM5 Route is route5
The menus table, as displayed via App Inspection aka Database Inspector :-

and the submenus table :-

uj5u.com熱心網友回復:
避免此錯誤的最簡單方法是向物體屬性添加默認值。
data class Menu(
val name: String = "",
val type: String = "",
val submenus: List<Submenu> = listOf<Submenu>()
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/349105.html
標籤:安卓 json android-room
