如何将 ByteBuffer 转换为 blob 以进行 cassandra 插入?

问题描述

我有一个 java.nio.ByteBuffer,我需要将它传递给一个 Cassandra 表,该表有一个字段作为 blob。

这是一个玩具示例的相关代码:

  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)

这个stackoverflow说使用“setList”:how to convert Scala List of bytes to blob

但是我没有字节列表,我有一个 ByteBuffer。此外,另一个问题是它告诉我 Cannot resolve overloaded method 'setList'

这个 StackOverflow 似乎可以回答我的问题,但有趣的是,他们实际上没有任何 cassandra 代码,这里全是关于包装的:https://codereview.stackexchange.com/questions/32556/storing-a-bytebuffer-into-a-cassandra-database

我认为这可能是我要找的东西,但我无法找到它们实际转换和插入 blob 的位置:https://github.com/DataStax-Examples/blobs-java/blob/master/src/main/java/com/datastax/examples/BlobsApp.java

编辑:我发现了这个,https://datastax-oss.atlassian.net/browse/JAVA-1325?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel

这似乎暗示我应该使用 setBytes。但是,我仍然收到 Cannot resolve overloaded method 'setBytes' 错误,所以我不知道是什么原因造成的。

解决方法

确切的解决方案可能取决于所用驱动程序的版本(3.x4.x)。

在最简单的情况下,您只需要执行(在调用 .bind 时指定所有参数):

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

或者你可以使用 .setBytes function(在 3.x 中)如果你想按名称绑定:

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

.setByteBuffer function(在 4.x 中)-注意它不进行就地分配而是返回一个新实例:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...