0
我有一個Grails項目與mongo數據庫交互。我想知道創建表示嵌套數據的域類的最佳做法。例如Grails和mongo數據庫嵌套數據結構
數據:
settings:{
user:{id:1234 , name:"john"}
colors:{header:"red" , footer:"white"}
}
希望得到任何幫助或代碼示例
我有一個Grails項目與mongo數據庫交互。我想知道創建表示嵌套數據的域類的最佳做法。例如Grails和mongo數據庫嵌套數據結構
數據:
settings:{
user:{id:1234 , name:"john"}
colors:{header:"red" , footer:"white"}
}
希望得到任何幫助或代碼示例
我認爲這是合理的假設您正在使用MongoDB的插件。
說得簡單:
Class Settings {
int user_id
String user_name
String colors_header
String colors_footer
}
如果有遺留的MongoDB集合像你呈現:
Class User {
int id
String name
}
Class Color {
String header
String footer
}
Class Settings{
User user
Colors colors
static embedded = ['user','colors']
}
因爲MongoDB是完全無模式就意味着你不侷限於固定數目的像關係數據庫中的列。所以創建嵌套數據相當容易。
這裏有一個例子:
//the domain class
class Settings {
Map user
Map colors
}
//in the groovy controller
def s = new Settings(user: [name:"jhon"],colors:[header:"red" ,footer:"white"])
s.save(flush: true)
感謝您的答覆,我使用的插件。我有點困惑,如果我使用你的第一個例子,在查詢時如何保留嵌套層次結構?你能給出一個代碼示例嗎? –
第一個定義不是嵌套的,而是簡化的扁平結構。如果你想嵌套的數據,只需要第二個,這與你的遺留數據結構相匹配。 – coderLMN