How can I store Objects in cassandra using the blob datatype

六月ゝ 毕业季﹏ 提交于 2020-01-13 20:23:49

问题


I tried with the data type blob. That's giving some Datastax exception. I tried the object itself, bytearray. Still no good:

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

This is the failing INSERT:

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("')"
                    + ";");

回答1:


From documentation

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

so what you need is provided by the Bytes class. The following is an interface I use to serialize/deserialize Java objects I need to save in Cassandra

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



来源:https://stackoverflow.com/questions/25197685/how-can-i-store-objects-in-cassandra-using-the-blob-datatype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!