1
votes

I have a java.nio.ByteBuffer, which I need to pass to a Cassandra table that has a field as a blob.

Here is the relevant code for a toy example:

  val ww = "65984jg3oiqh4g3q383423932824344"
  val www = getBytes(ww)
  val wwww = LongTupleHashFunction.xx128().hashBytes(www)
  val wwwww = ByteBuffer.allocate(128).putLong(wwww(0)).putLong(wwww(1))
  wwwww.order(ByteOrder.BIG_ENDIAN)

  val d_q = "DROP TABLE example.test "
  val t_q = "CREATE TABLE example.test (hash_aggregation_key blob, PRIMARY KEY (hash_aggregation_key)) "

  cassandraSession.execute(d_q)
  cassandraSession.execute(t_q)

  val ps: PreparedStatement = cassandraSession.prepare("insert into " + Constants.FEATURE_KEYSPACE + "." +
    Constants.FEATURE_TABLE + "(hash_aggregation_key) VALUES(?) USING TTL 100000")
  val bStatement: BoundStatement = ps.bind
  bStatement.setList("hash_aggregation_key",wwwww)
  cassandraSession.execute(bStatement)

This stackoverflow said to use "setList": how to convert Scala List of bytes to blob

But I don't have a list of bytes, I have a ByteBuffer. Also, another issue is that it tells me Cannot resolve overloaded method 'setList'.

This StackOverflow seemed like it would answer my question, but hilariously enough they don't actually have any cassandra code in here it's all about the wrappings: https://codereview.stackexchange.com/questions/32556/storing-a-bytebuffer-into-a-cassandra-database

I THINK this might have what I'm looking for, but I'm having trouble finding where they actually convert and insert a blob: https://github.com/DataStax-Examples/blobs-java/blob/master/src/main/java/com/datastax/examples/BlobsApp.java

EDIT: I found this, https://datastax-oss.atlassian.net/browse/JAVA-1325?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel

Which seems to be implying I should use setBytes. However, I still get the Cannot resolve overloaded method 'setBytes' error, so I'm confused as to what's causing that.

1

1 Answers

1
votes

Exact solution may depend on the version of the driver used (3.x vs 4.x).

In the simplest case you just need to do (specify all arguments when calling .bind):

val bStatement: BoundStatement = ps.bind(wwwww)
cassandraSession.execute(bStatement)

Or you can use .setBytes function (in 3.x) if you want to bind by name:

val bStatement: BoundStatement = ps.bind
bStatement.setBytes("hash_aggregation_key",wwwww)
cassandraSession.execute(bStatement)

or .setByteBuffer function (in 4.x) - notice that it doesn't do in-place assignment but returns a new instance:

val bStatement: BoundStatement = ps.bind.setByteBuffer("hash_aggregation_key",wwwww)
cassandraSession.execute(bStatement)