OrientDB Object API中的Joda DateTime

时间:2017-09-12 15:00:30

标签: java orientdb

我使用的是JDK 8,JodaTime 2.9.9和OrientDB 2.2.26。

有没有办法在OrientDB Object API中使用DateTime对象?

示例类:

class Entity {

    private DateTime date;

    public Entity(DateTime date){
        this.date = date
    }

    public DateTime getDate(){
        return date;
    }

    public void setDate(DateTime newDate){
        this.date = newDate;
    }
}

在OrientDB注册:

database.getEntityManager().registerEntityClass(Entity)

如果我试图保存它:

database.save(new Entity(DateTime.now()))

然后我得到:

com.orientechnologies.orient.core.exception.OSerializationException: 
Linked type [class org.joda.time.DateTime:2017–09–12T11:50:25.709–03:00] 
cannot be serialized because is not part of registered entities.

如果我尝试注册DateTime:

database.getEntityManager().registerEntityClass(DateTime)

我试图再次保存实体:

database.save(new Entity(DateTime.now()))

由于它是一个最终类,javassist无法代理它,所以我得到了一个:

java.lang.RuntimeException: org.joda.time.DateTime is final

我不想改变我的类来存储长而不是DateTime。有没有办法为DateTime实现和注册某种序列化器和反序列化器,或类似地,不会干扰我的实体?

1 个答案:

答案 0 :(得分:0)

好的,我发现了如何做到这一点(Groovy中的代码):

    def orientDbServer = OServerMain.create()
    System.setProperty("ORIENTDB_HOME", new File("").getAbsolutePath());
    orientDbServer.startup(new OServerConfiguration().with { cfg ->
        location = "memory"
        network = new OServerNetworkConfiguration(this)
        users = [new OServerUserConfiguration(name: "root", 
                                              password: "root",
                                              resources: "*")] as OServerUserConfiguration[]
        cfg
    })
    orientDbServer.activate()

    addShutdownHook {
        orientDbServer.shutdown()
    }

    new OServerAdmin("localhost").connect("root", "root")
                                 .createDatabase("test", "document", "memory").close()
    OObjectDatabaseTx database = 
                    new OObjectDatabaseTx("memory:localhost/test").open("admin", "admin")

    OObjectSerializerContext serializerContext = new OObjectSerializerContext();
    serializerContext.bind(new OObjectSerializer<DateTime, Long>() {
        @Override
        Object serializeFieldValue(Class<?> iClass, DateTime iFieldValue) {
            return iFieldValue.getMillis()
        }

        @Override
        Object unserializeFieldValue(Class<?> iClass, Long iFieldValue) {
            return new DateTime(iFieldValue)
        }
    }, database)

    OObjectSerializerHelper.bindSerializerContext(null, serializerContext)

在任何实体类注册

之前注册serializerContext非常重要