cassandra java binding a collection of maps to a prepared statement

I am using datastax' Cassandra Java driver. My Cassandra supports CQL 2 only. I have a prepared INSERT statement that needs to accept a list of maps. This is my schema:

CREATE TYPE test.snap_guid ( l bigint, h bigint ); CREATE TABLE test.t ( id bigint, snap list>, PRIMARY KEY ((id)) ) 
This is the prepared statement:
PreparedStatement mysttmt = .prepare("INSERT INTO test.t (id, snap) VALUES (?, ?)"); 

I know that in order to bind collections to the prepared statement I need to create a collection, and bind it. I cannot put the collection brackets in the prepared query. For instance (for list of text):

ArrayList snaps = new ArrayList<>(); snaps.add("AEF34GF665"); // INSERT INTO test.t (id, snap) VALUES (?, ?) BoundStatement bs = mysttmt.bind(12, snaps); 
My question is: how do I bind a list of maps? How can I create a query like the next one?
INSERT INTO test.t (id, snap) VALUES (12, []) // I know it is impossible to create the following prepared statement: INSERT INTO test.t (id, snap) VALUES (?, []) // The list of maps has to be a single bound variable. how. INSERT INTO test.t (id, snap) VALUES (?, ?) 
15.9k 2 2 gold badges 20 20 silver badges 28 28 bronze badges asked Nov 10, 2016 at 16:42 1,109 1 1 gold badge 12 12 silver badges 17 17 bronze badges

2 Answers 2

  1. Create tables:
CREATE TYPE my_type ( user_id text, name text, age bigint ); CREATE TABLE my_table_with_set_of_udt ( my_key text PRIMARY KEY, my_types set> ); CREATE INDEX ON my_table_with_set_of_udt(my_types); 
@UDT(keyspace = "my_ks", name = "my_type") public class MyType < @Field(name = "user_id") private String userId; @Field(name = "name") private String name; @Field(name = "age") private int age; // getters, setters & constructors // equals & hashCode are required for a set >@Table(keyspace = "my_ks", name = "my_table_with_set_of_udt") public class MyTableWithSetOfUDT < @PartitionKey @Column(name = "my_key") private String myKey; @Column(name = "my_types") @FrozenValue // because of -->set> private Set myTypes; // getters, setters & constructors // equals & hashCode are required for a set > @Bean public Mapper myTableWithSetOfUDTMapper() < return new MappingManager(cassandraClient.getSession()).mapper(MyTableWithSetOfUDT.class); >@Bean public UDTMapper myTypeMapper()
addUpdateStatement = cassandraClient.getSession().prepare("UPDATE my_table_with_set_of_udt SET my_types = my_types + ? WHERE my_key=?;"); deleteUpdateStatement = cassandraClient.getSession().prepare("UPDATE my_table_with_set_of_udt SET my_types = my_types - ? WHERE my_key=?;"); 
MyType myType = MyType(userId, name, age); UDTValue value = myTypeMapper.toUDT(myType); cassandraClient.getSession().execute(addUpdateStatement.bind(Sets.newHashSet(value), myKey)); 
cassandraClient.getSession().execute(deleteUpdateStatement.bind(Sets.newHashSet(value), myKey));