Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store Objects in cassandra using the blob datatype

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("')"
                    + ";");
like image 264
najeeb Avatar asked Mar 18 '23 19:03

najeeb


1 Answers

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

like image 165
Carlo Bertuccini Avatar answered May 08 '23 04:05

Carlo Bertuccini