【问题标题】:How can I store Objects in cassandra using the blob datatype如何使用 blob 数据类型在 cassandra 中存储对象
【发布时间】:2014-10-01 14:10:01
【问题描述】:

我尝试使用数据类型blob。这给了一些 Datastax 例外。我尝试了对象本身,bytearray。还是不行:

 Caused by: com.datastax.driver.core.exceptions.InvalidQueryException: Invalid STRING constant ([B@547248ad) for user_object of type blob

这是失败的插入:

executeSting.append("INSERT INTO htadb.objecttable (object_id, bucket_name, object_key, link, user_status, user_object) ")
            .append("VALUES (")
            .append(objectId).append(",'")
            .append(bucketName).append("','")
            .append(key).append("','")
            .append(link).append("','")
            .append("online").append("','")
            .append(serializer(register)).append("')"
                    + ";");

【问题讨论】:

标签: cassandra datastax-java-driver


【解决方案1】:

来自文档

blob  | blobs  |  Arbitrary bytes (no validation), expressed as hexadecimal

所以你需要的由Bytes 类提供。以下是我用来序列化/反序列化需要保存在 Cassandra 中的 Java 对象的接口

public interface Bufferable extends Serializable {

    static final Logger LOGGER = LoggerFactory.getLogger(Bufferable.class);

    default ByteBuffer serialize() {
        try (ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bytes);) {
            oos.writeObject(this);
            String hexString = Bytes.toHexString(bytes.toByteArray());
            return Bytes.fromHexString(hexString);
        } catch (IOException e) {
            LOGGER.error("Serializing bufferable object error", e);
            return null;
        }
    }

    public static Bufferable deserialize(ByteBuffer bytes) {
        String hx = Bytes.toHexString(bytes);
        ByteBuffer ex = Bytes.fromHexString(hx);
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(ex.array()));) {
            return (Bufferable) ois.readObject();
        } catch (ClassNotFoundException | IOException e) {
            LOGGER.error("Deserializing bufferable object error", e);
            return null;
        }
    }
}

HTH, 卡罗

【讨论】:

  • 感谢 Carlo 的回答,我使用上面的代码仍然得到相同的异常原因:com.datastax.driver.core.exceptions.InvalidQueryException: Invalid STRING constant ([B@547248ad) for blob 类型的 user_object 。我认为这是我的查询错误。添加我的查询代码请检查
  • 我不明白你的查询——使用边界语句,你应该在你的 BS 上调用 setBytes() 并传递 ByteBuffer
【解决方案2】:

您可以使用 java.nio.ByteBuffer.wrap() 包装您的 Array[Byte] 对象

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2018-08-25
    • 2020-09-03
    • 2016-10-02
    • 2021-09-18
    相关资源
    最近更新 更多