【问题标题】:Datanucleus/mongodb: Persisting map of listsDatanucleus/mongodb:列表的持久化映射
【发布时间】:2013-07-09 16:18:22
【问题描述】:

我正在使用 datanucleus 3.2.5 / JDO 将对象持久保存到 MongoDB 数据库。

在尝试保留一张列表地图时,出现以下异常:

RuntimeException: json can't serialize type [list element type here]

一些示例代码:

@PersistenceCapable
public class SomeClass {
    private Map<String, List<SomeOtherClass>> myAttribute;
    // ...
}


@PersistenceCapable(embeddedOnly="true")
public class SomeOtherClass {
    private String attribute;
    // ...
}

我可以通过将嵌入属性注释为@Serialized 来解决这个问题,但我更喜欢更优雅的方式。

我错过了什么吗?有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: java mongodb jdo datanucleus


    【解决方案1】:

    在 DataNucleus 论坛中引用 Andy 的 reply 来回答我的问题:

    没有持久性规范定义对容器的容器的任何支持。始终建议您将内部容器(在您的情况下为 List)作为中间类的字段。

    所以这里有两种方法:

    使用中间类

    迄今为止最优雅和可维护的解决方案。按照示例玩具代码:

    @PersistenceCapable
    public class SomeClass {
        private Map<String, SomeOtherClassContainer> myAttribute;
        // ...
    }
    
    @PersistenceCapable(embeddedOnly="true")
    public class SomeClassContainer {
        private List<SomeOtherClass> myAttribute;
        // ...
    }
    
    @PersistenceCapable(embeddedOnly="true")
    public class SomeOtherClass {
        private String attribute;
        // ...
    }
    

    将属性标记为@Serializable

    丑陋,可能是头痛的根源,特别是如果依赖java default serialization

    @PersistenceCapable
    public class SomeClass {
        @Serializable
        private Map<String, List<SomeOtherClass>> myAttribute;
        // ...
    }
    
    @PersistenceCapable(embeddedOnly="true")
    public class SomeOtherClass implements Serializable {
        private String attribute;
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2017-05-07
      • 2023-03-16
      相关资源
      最近更新 更多