How to store objects in cassandra using blob data type

I tried with the blob data type. This gives a Datastax exception. I tried the object itself, bytearray. Nothing good yet:

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

This is a failed 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("')" + ";"); 
+2
source share
1 answer

From the documentation

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

so you need a Bytes class. Below is the interface that I use to serialize / deserialize Java objects that 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; } } } 

NTN, Carlo

+6
source

Source: https://habr.com/ru/post/973965/


All Articles