zoukankan      html  css  js  c++  java
  • Storing Java objects in MySQL blobs

    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 {

  • 相关阅读:
    urql 高度可自定义&&多功能的react graphql client
    使用vault pki 为nginx 生成tls 证书文件
    使用vault pki engine 方便的管理证书
    使用terraform 生成自签名证书
    Kapitan 通用terraform&& kubernetes 配置管理工具
    sqler 集成 terraform v0.12 生成资源部署文件
    检查cgroup v2 是否安装
    centos 较新版本kernel安装方法
    tbls ci 友好的数据库文档化工具
    graphql-query-rewriter 无缝处理graphql 变更
  • 原文地址:https://www.cnblogs.com/fwjybfq/p/7003442.html
Copyright © 2011-2022 走看看