自制与Java序列化 [英] Homemade vs. Java Serialization

查看:176
本文介绍了自制与Java序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在数据库上持久化的POJO,当前设计将其字段指定为单个字符串列,并且向表中添加其他字段不是一个选项。

I have a certain POJO which needs to be persisted on a database, current design specifies its field as a single string column, and adding additional fields to the table is not an option.

意思是,对象需要以某种方式序列化。所以只是为了基本的实现,我去设计了我自己的对象的序列化形式,这意味着将它的所有字段串联成一个很好的字符串,由我选择的分隔符分隔。

Meaning, the objects need to be serialized in some way. So just for the basic implementation I went and designed my own serialized form of the object which meant concatenating all it's fields into one nice string, separated by a delimiter I chose. But this is rather ugly, and can cause problems, say if one of the fields contains my delimiter.

所以我试过基本的Java序列化,但从一个基本的测试我进行了,这不知何故成为一个非常昂贵的操作(构建一个ByteArrayOutputStream,一个ObjectOutputStream,等等,反序列化相同)。

So I tried basic Java serialization, but from a basic test I conducted, this somehow becomes a very costly operation (building a ByteArrayOutputStream, an ObjectOutputStream, and so on, same for the deserialization).

那么我的选择是什么?

So what are my options? What is the preferred way for serializing objects to go on a database?

编辑:这将是我的项目中非常常见的操作,因此开销必须保持最小,性能至关重要。另外,第三方解决方案很好,但不相关(通常会产生我想避免的开销)

this is going to be a very common operation in my project, so overhead must be kept to a minimum, and performance is crucial. Also, third-party solutions are nice, but irrelevant (and usually generate overhead which I am trying to avoid)

推荐答案

Elliot Rusty Harold写了一个不错的参数,针对他的XOM库中的对象使用Java对象序列化。同样的原则适用于你。内置的Java序列化是Java特定的,脆弱的和缓慢的,所以最好避免。

Elliot Rusty Harold wrote up a nice argument against using Java Object serialization for the objects in his XOM library. The same principles apply to you. The built-in Java serialization is Java-specific, fragile, and slow, and so is best avoided.

在使用基于字符串的格式。正如你所说,问题是你正在使用分隔符的格式化/语法问题。解决方案是使用已经构建的格式来处理这个问题。如果这是一个标准化的格式,那么你也可以使用其他库/语言来操作它。此外,基于字符串的格式意味着你希望通过眼球数据理解它;二进制格式删除该选项。

You have roughly the right idea in using a String-based format. The problem, as you state, is that you're running into formatting/syntax problems with delimiters. The solution is to use a format that is already built to handle this. If this is a standardized format, then you can also potentially use other libraries/languages to manipulate it. Also, a string-based format means that you have a hope of understanding it just by eyeballing the data; binary formats remove that option.

XML和JSON是两个很好的选择;它们是标准化的,基于文本的,灵活的,可读的,并且有大量的库支持。它们也会出奇地良好(有时甚至比Java序列化更快)

XML and JSON are two great options here; they're standardized, text-based, flexible, readable, and have lots of library support. They'll also perform surprisingly well (sometimes even faster than Java serialization).

这篇关于自制与Java序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆