I'm using Cassandra Driver 2.0.0-beta2 with Cassandra 2.0.1.

I want to set a NULL value to a column of type 'int', in a BoundStatement. I don't think I can with setInt.

This is the code I'm using:

String insertStatementString = "insert into subscribers(subscriber,start_date,subscriber_id)";
PreparedStatement insertStatement = session.prepare(insertStatementString);
BoundStatement bs = new BoundStatement(insertStatement);
bs.setString("subscriber",s.getSubscriberName());
bs.setDate("start_date",startDate);
bs.setInt("subscriber_id",s.getSubscriberID());

The last line throws a null pointer exception, which can be explained because s.getSubscriberID() return an Integer and the BoundStatement accepts only ints, so when the id is null, it can't be converted, thus the exception.

The definition in my opinion should change to:

BoundStatement.setInt(String name, Integer v);

The way it is right now, I can't set NULL values for numbers.

Or am I missing something? Is there other way to achieve this?

In cqlsh, setting null to a column of type 'int' is possible.

有帮助吗?

解决方案

There is no need to bind values where the value will be empty or null. Therefore a null check might be useful, e.g.,

if(null != s.getSubscriberID()){
  bs.setInt("subscriber_id",s.getSubscriberID());
}

As to the question of multiple instantiations of BoundStatement, the creation of multiple BoundStatement will be cheap in comparison with PreparedStatements (see the CQL documentation on prepared statements). Therefore the benefit is more clear when you begin to reuse the PreparedStatement, e.g., with a loop

String insertStatementString = "insert into subscribers(subscriber,start_date,subscriber_id)";
PreparedStatement insertStatement = session.prepare(insertStatementString);

// Inside a loop for example
for(Subscriber s: subscribersCollection){
  BoundStatement bs = new BoundStatement(insertStatement);
  bs.setString("subscriber",s.getSubscriberName());
  bs.setDate("start_date",startDate);
  if(null != s.getSubscriberID()){
    bs.setInt("subscriber_id",s.getSubscriberID());
  }
  session.execute(bs);
}

其他提示

I decided not to set the value at all. By default, it is null. It's a weird workaround.

But now I have to instantiate the BoundStatement before every call, because otherwise I risk having a value different than null from a previous call.

It would be great if they added a more comprehensive 'null' support.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top