मैं समझाऊंगा कि कैसे अलग-अलग क्षेत्रों को एक उदाहरण के साथ संभाला जाता है। निम्नलिखित Game.java POJO वर्ग game के लिए ऑब्जेक्ट मैपिंग का प्रतिनिधित्व करता है संग्रह दस्तावेज।
public class Game {
String name;
List<Actions> actions;
public Game(String name, List<Actions> actions) {
this.name = name;
this.actions = actions;
}
public String getName() {
return name;
}
public List<Actions> getActions() {
return actions;
}
// other get/set methods, override, etc..
public static class Actions {
Integer id;
String type;
public Actions() {
}
public Actions(Integer id) {
this.id = id;
}
public Actions(Integer id, String type) {
this.id = id;
this.type = type;
}
public Integer getId() {
return id;
}
public String getType() {
return type;
}
// other methods
}
}
Actions . के लिए कक्षा आपको संभावित संयोजनों के साथ रचनाकार प्रदान करने की आवश्यकता है। id . के साथ उपयुक्त कंस्ट्रक्टर का उपयोग करें , type , आदि। उदाहरण के लिए, एक game create बनाएं ऑब्जेक्ट करें और डेटाबेस में सहेजें:
Game.Actions actions= new Game.Actions(new Integer(1000));
Game g1 = new Game("G-1", Arrays.asList(actions));
repo.save(g1);
यह डेटाबेस संग्रह game . में संग्रहीत है इस प्रकार है (mongo . से पूछा गया) खोल):
{
"_id" : ObjectId("5eeafe2043f875621d1e447b"),
"name" : "G-1",
"actions" : [
{
"_id" : 1000
}
],
"_class" : "com.example.demo.Game"
}
actions नोट करें सरणी। जैसा कि हमने केवल id . संग्रहित किया था Game.Actions . में फ़ील्ड ऑब्जेक्ट, केवल वह फ़ील्ड संग्रहीत है। भले ही आप कक्षा में सभी फ़ील्ड निर्दिष्ट करते हैं, केवल वे ही मान के साथ प्रदान किए जाते हैं।
ये Game.Actions . के साथ दो और दस्तावेज़ हैं type . के साथ बनाया गया केवल और id + type उपयुक्त कंस्ट्रक्टर्स का उपयोग करना:
{
"_id" : ObjectId("5eeb02fe5b86147de7dd7484"),
"name" : "G-9",
"actions" : [
{
"type" : "type-x"
}
],
"_class" : "com.example.demo.Game"
}
{
"_id" : ObjectId("5eeb034d70a4b6360d5398cc"),
"name" : "G-11",
"actions" : [
{
"_id" : 2,
"type" : "type-y"
}
],
"_class" : "com.example.demo.Game"
}