Storing Java objects in MySQL blobs

本文介绍如何使用PreparedStatement将Java中的可序列化对象存储到MySQL数据库的BLOB字段中,并通过ObjectInputStream实现对象的反序列化读取。

Storing Java objects in MySQL blobs
It's easy to store any serializable object in a blob in a MySQL database, if you use a PreparedStatement:

String query="replace into mysession (personid,data) values (?,?)";
PreparedStatement statement=conn.prepareStatement(query);
statement.setInt(1, ses.getPersonid());
statement.setObject(2, (Object)ses);
statement.execute();
When you try to retrieve the object, it gets work. It's supposed to work like this, using getObject():

query="select data from mysession where personid=? and time_to_sec(timediff(now(), datum)) < 600";
statement=conn.prepareStatement(query);
statement.setInt(1, personid);
resultSet = statement.executeQuery();
if (resultSet.next()) {
Object x=resultSet.getObject(1);
ses = (MySession)x;
} else {
However, the responsibility for deserializing the blob so that getObject() succeeds, lies with the database driver, and MySQL doesn't do this automatically.

You do get an Object back, and everything looks fine, but the class name of the object (read with o.getClass().toString()) is just garbage, containing stuff like "[B", and when you try to cast it to your own class you get a classCastException.

To make the MySQL driver deserialize blobs, you are supposed to add a parameter, "autoDeserialize=true", to your JDBC URL.

Unfortunately, the MySQL driver appears to exist in its own context, oblivious to any user-defined classes. Making your own classes globally available is usually not a good idea, so instead you can use an ObjectInputStream:

query="select data from mysession where personid=? and time_to_sec(timediff(now(), datum)) < 600";
statement=conn.prepareStatement(query);
statement.setInt(1, personid);
resultSet = statement.executeQuery();
if (resultSet.next()) {
InputStream is = resultSet.getBlob("data").getBinaryStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object x = ois.readObject();
ses = (MySession)x;
} else {

转载于:https://www.cnblogs.com/fwjybfq/p/7003442.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值