Cassandra says "InvalidQueryException: Invalid version for TimeUUID type" when saving java.util.UUID
Asked Answered
Z

1

5

I'm trying to save java.util.UUID to Cassandra column of type timeuuid. For example, that is a default spring-data-cassandra mapping: http://docs.spring.io/spring-data/cassandra/docs/current/reference/html/#mapping-conversion . Value of UUID is generated by java.util.UUID#randomUUID() I get an exception: "com.datastax.driver.core.exceptions.InvalidQueryException: Invalid version for TimeUUID type"

Studying code at https://svn.apache.org/repos/asf/cassandra/trunk/src/java/org/apache/cassandra/db/marshal/TimeUUIDType.java reveals the reason:

    @Override
    public void validate(byte[] bytes)
    {
        if (bytes.length != 16 && bytes.length != 0)
            throw new MarshalException(String.format("TimeUUID should be 16 or 0 bytes (%d)", bytes.length));
        // version is bits 4-7 of byte 6.
        if (bytes.length > 0)
            if ((bytes[6] & 0xf0) != 0x10)
                throw new MarshalException("Invalid version for TimeUUID type.");
    }
Zyrian answered 14/3, 2017 at 16:40 Comment(0)
Z
8

That means that Cassandra timeuuid type accepts only time-based UUIDs. Value that is generated by java.util.UUID#randomUUID() is type 4 (pseudo randomly generated) UUID and does not pass validation. So TimeUUID class works as expected, but the exception cause is not so obvious. Possible workarounds:

  1. You should insert the timeuuid generated via datastax driver. In your case , since you are using version 1 timeuuid, you must use UUIDs.timeBased() .

Source: https://stackoverflow.com/a/23198388

  1. Or if you are mapping entity through spring-data-cassandra and need to save UUIDs supplied by third-party, add to entity field the annotation @CassandraType(type = DataType.Name.UUID)
Zyrian answered 14/3, 2017 at 16:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.