valchkou / cassandra-driver-mapping

JPA addon for DataStax Java Driver for Cassandra
58 stars 24 forks source link

How can I use C*-side generation of UUID and TimeUUID? #41

Closed crazyproger closed 9 years ago

crazyproger commented 9 years ago

I want make some handy save method on top of your API. Main idea is when entity does not have ID and it is of type UUID(90% case, i think) - let C* generate it on save, e.g. execute query like this: insert into stuff (uid, name) values(now(), 'my name');

I didn't find how to do this in project wiki. Can I do this in some way?

valchkou commented 9 years ago

UUID is very simple:

declare property as UUID: private UUID id; you can generate uuid as id = UUID.randomUUID();

TimeUUID more tricky as java has no built in support for it:

<dependency>
    <groupId>com.eaio.uuid</groupId>
    <artifactId>uuid</artifactId>
    <version>3.2</version>
</dependency>
import java.util.Date;
import java.util.UUID;

public class DateUtil {
    private static final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L;

    public static Date timeUUID2Date(UUID uuid) {
        long time = (uuid.timestamp() - NUM_100NS_INTERVALS_SINCE_UUID_EPOCH) / 10000;
        return new Date(time);
    }
}
crazyproger commented 9 years ago

hmm, thanks. Interesting, but, I thought about calling CQL function. What you think, if I will make a pull-request with this possibility - can it be accepted by ideology of this project and integrated to it?

valchkou commented 9 years ago

OH sorry, got it, I was thinking to do it while back

valchkou commented 9 years ago

you are more than welcome to add such feature. I am thinking of custom annotation @TimeUUID instead of @Column(columnDefinition="timeuuid") with boolean optional parameter autogenerate or autosave. When set to true CQL will have now().

Another option (probably easier one) would be just to check if uuid is not set on entity then enchance CQL with the function now().

valchkou commented 9 years ago

available on mvn central. if uuid or timeuuid is a part of key and value is not set then C* functions uuid() or now() respectively will be used on insert. There is drowback though. The generated value will not be returned within save() operation.

valchkou commented 9 years ago

Default behavior is not to auto generate value. Autogen turned on only if id property annotated as @GeneratedValue

crazyproger commented 9 years ago

Oh, sadly to hear that generated values will not be returned. Very disappointing CQL limitation. But TimeUUID still helpful for clustering key fields when row used as smth like a timeline of events. Thanks for this feature.