从对象创建对象输出流
我想在 ObjectOutputStream
上创建,但我不想将对象保留在文件中,那么该怎么做呢?所有教程(我找到的)都只说了文件方式:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new Date());
oos.close();
我想将对象存储到数据库中,所以我需要在类 PreparedStatement 的方法
。setBinaryStream()
中指定一个流
谢谢您的回答...
I want to create on ObjectOutputStream
, but I don't want to persist the object in a file, so how to do that? All the tutorials(that I found) say only about the file way:
FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new Date());
oos.close();
I want to store the object into a database, so I need to specify a stream in method setBinaryStream()
from class PreparedStatement
.
Thanks for answering...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
而是将其存储在字节数组中。您可以使用
ByteArrayOutputStream
PreparedStatement#setBytes()
。也就是说,这是一个非常好的气味。您确定需要将 Java 对象序列化到数据库中吗?这样它们就无法索引且无法搜索。例如,如果您将序列化的每个
Person
存储在数据库中,则无法再执行SELECT * FROM person WHERE name = 'John'
操作。通常的做法是对实体和数据库表进行 1:1 的映射。例如,Date
可以完美地存储在DATETIME
/TIMESTAMP
列中。Store it in a byte array instead. You can use
ByteArrayOutputStream
for this. This way you can usePreparedStatement#setBytes()
.That said, this is pretty a good smell. Are you sure that you need to serialize Java objects into a database? This way they are unindexable and unsearchable. If you for example store each
Person
serialized in the DB, you cannot doSELECT * FROM person WHERE name = 'John'
anymore. The normal practice is to do a 1:1 mapping of the entity and the DB table. TheDate
for example can perfectly be stored in aDATETIME
/TIMESTAMP
column.现在你有了一个字节数组并用它做你想做的事情。
So now you have a byte array and do what you want with it.
您特别需要使用输出流写入数据库?在尝试编写输出流实现之前,我会认真考虑查看持久性 api。因为连接详细信息等可能很难管理。
查看 链接文本 并记住它可以在 J2SE 中用作出色地。
you specifically need to use an outputstream to write to a database? I would seriously consider looking at the persistence api before attempting to write an outputstream implementation.. since connection details etc, might get tricky to manage.
have a look at link text and remember it can be used in J2SE as well.