InvalidTypeException:CQL类型文本的值1的类型无效,期望类java.lang.String但类[Ljava.lang.Object;提供

时间:2013-12-07 20:54:38

标签: java cassandra cql datastax-java-driver

我正在尝试使用Datastax Java驱动程序插入到Cassandra数据库中。但每次我在prBatchInsert.bind行 -

以下时都会遇到异常
com.datastax.driver.core.exceptions.InvalidTypeException: Invalid type for value 1 of CQL type text, expecting class java.lang.String but class [Ljava.lang.Object; provided

以下是我的方法,该方法接受userId作为输入,attributes作为Map,其中包含key作为Column Name,值为实际值该栏目

public void upsertAttributes(final String userId, final Map<String, String> attributes, final String columnFamily) {

    try {
        Set<String> keys = attributes.keySet();
        StringBuilder sqlPart1 = new StringBuilder(); //StringBuilder.append() is faster than concatenating Strings in a loop
        StringBuilder sqlPart2 = new StringBuilder();

        sqlPart1.append("INSERT INTO " + columnFamily + "(USER_ID ");
        sqlPart2.append(") VALUES ( ?");

        for (String k : keys) {
            sqlPart1.append(", "+k); //append each key
            sqlPart2.append(", ?");  //append an unknown value for each key
        }
        sqlPart2.append(") "); //Last parenthesis (and space?)
        String sql = sqlPart1.toString()+sqlPart2.toString();

        CassandraDatastaxConnection.getInstance();
        PreparedStatement prBatchInsert = CassandraDatastaxConnection.getSession().prepare(sql);
        prBatchInsert.setConsistencyLevel(ConsistencyLevel.ONE);        

        // this line is giving me an exception
        BoundStatement query = prBatchInsert.bind(userId, attributes.values().toArray(new Object[attributes.size()])); //Vararg methods can take an array (might need to cast it to String[]?).

        CassandraDatastaxConnection.getSession().executeAsync(query);

    } catch (InvalidQueryException e) {
        LOG.error("Invalid Query Exception in CassandraDatastaxClient::upsertAttributes "+e);
    } catch (Exception e) {
        LOG.error("Exception in CassandraDatastaxClient::upsertAttributes "+e);
    }
}

我在这做错了什么?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要将userId字符串与对象数组合并,因为您现在传递它的方式被视为[string, object array]而java不喜欢它。

// instead of 
// BoundStatement query = prBatchInsert.bind(userId, attributes.values().toArray(new Object[attributes.size()])); 

// try, first combining the uid to the map of values 
Collection<Object> params = new ArrayList<Object>(attributes.size() + 1);
params.add(userId);
for(Object o : attributes.values().toArray())
    params.add(o);

// then passing in the new collection as an array
BoundStatement query = prBatchInsert.bind(params.toArray());