Harshad Vyawahare
Harshad Vyawahare

Reputation: 608

Autogenerate UUID or timeuuid in spring-data Cassandra?

I am using spring-data-cassandra. Is there a way or an annotation, which can be used in my entity java POJO for the primary key of type uuid or timeuuid,to auto-generate the value of the primary key(id)?

I know that I can use id = UUIDs.timeBased();, but I want to automate it.

Upvotes: 3

Views: 7609

Answers (2)

Vikas Sachdeva
Vikas Sachdeva

Reputation: 5803

Although, id can be initialized in default constructor. However, it will result in unnecessary generation of UUIDs.

One better approach is to exploit multiple constructor of the POJO class -

Default constructor -

public MyEntity() {

}

Parametrized constructor - Pass all the fields except id field in constructor. This constructor should be called in application code. Type and no. of fields can vary -

public MyEntity(String field1) {
     this.field1 = field1;
     this.id = UUIDs.timeBased();
}

One major benefit of using this approach is - default constructor is used by Spring for mapping CQL with POJO class, for example in SELECT query response.

So, by this way, unnecessary generation of UUID can be avoided by Spring framework and some optimization can be done.

Upvotes: 3

Ztyx
Ztyx

Reputation: 14939

You could always implement the default constructor:

MyEntity() {
    id = UUIDs.timeBased();
}

Would that be enough? This would obviously require an unnecessary generation on instantiation which would consume some random entropy on your system. However, if your system is not running with too much high pressure you should be safe.

Upvotes: 8

Related Questions