使用Morphia保存复杂对象

时间:2018-01-13 18:47:41

标签: java database mongodb morphia

我想将复杂对象保存为另一个对象A的属性,但是我无法使它工作(我收到CodecConfigurationException,因为MongoDB不支持我的B对象)

@Entity(value = "someCollection", noClassnameStored = true)
public class User {
    @Id
    private final String key = UUID.randomUUID().toString();
    private int age = 27;
    private String boss = "no info";
    public Map<String, Object> ownedItems = new HashMap<>();
}

public class Apple {
    private int variable = 6, variable2 = 9;
    private String randomQuotation = "Oh, hi Mark";
}

public class HybridCar {
    private int wheels = 4, speed = 260;
}

public class Main {
    public static void main(String... args){
        MongoClient mongo = new MongoClient();
        Morphia morphia = new Morphia();
        morphia.map(User.class);

        User user = new User();
        user.ownedItems.put("Rabbit", new Apple());
        user.ownedItems.put("Tortoise", new HybridCar());

        morphia.createDatastore(mongo, "someDatabase").save(user);
    }
}

我想得到这样的结果:

 - someDatabase:
     - someCollection:
         - (some random uuid as "User" "name"):
             - age: 27
             - boss: no info
             - ownedItems:
                 - Rabbit:
                     - variable: 6
                     - variable2: 9
                     - randomQuotation: Oh, hi Mark
                 - Tortoise:
                     - wheels: 4
                     - speed: 200

如何实现呢? 我知道有一些像@Embeed这样的东西,但只有当对象被保存为自变量而不是map的元素时才会有效。 我不明白这一切是如何运作的。我会非常感谢一些代码或提示。 求求你,不要写“看看morphia docs”,因为我已经失去了4个小时,我感觉很蓝:(

1 个答案:

答案 0 :(得分:0)

你需要添加

  

@Embedded

嵌入对象的注释

@Entity(value = "someCollection", noClassnameStored = true)
public class User {
    @Id
    private final String key = UUID.randomUUID().toString();
    private int age = 27;
    private String boss = "no info";
    @Embedded("ownedItems")
    public Map<String, Object> ownedItems = new HashMap<>();
}