1

我正在尝试使用 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输入和包含attributesMapkey作为我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);
    }
}

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

4

1 回答 1

1

You need to combine the userId string to the object array, because the way you are passing it now is being seen as [string, object array] and java doesn't like that.

// 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());
于 2013-12-07T21:57:08.537 回答