Wednesday, August 19, 2015

Customizing spring-data-cassandra to support TTL

The REST service I mentioned previously uses Cassandra for data storage and talks to it using Spring Data Cassandra (1.2.2). Integrating with it was easy peasy, all it took is a couple of beans in configuration, and a couple of Repository interfaces (which caused some problems with Spring Boot as I described in this post). But then a new requirement came in, columns in Cassandra had to be inserted with TTL (time to live). CrudRepository methods don't support TTL. In order to support TTL during insertion, save method has to be able to take ttl as a parameter. I wanted to implement this functionality once for all repositories in the application. As described in the documentation2 classes needed to be created:

Interface MyRepository, where I added another save method:
Class MyRepositoryImpl, where the method was implemented:

Notice that the documentation is for JPA repositories. For Cassandra repository one more step was needed (I did not find the way around it). Reporsitory Factory Bean needed to be created: and it had to be defined in Configuration: Now we can define a Repository, e.g : Then we just autowire it and call it:

6 comments:

  1. Hello

    I tried above code but i am getting following error:
    Caused by: java.lang.IllegalArgumentException: encountered unsupported query parameter type [class java.lang.Object] in method public abstract java.lang.Object com.cisco.operation.CustomTTLRepository.save(java.lang.Object,int)
    at org.springframework.data.cassandra.repository.query.CassandraQueryMethod.verify(CassandraQueryMethod.java:104)
    at org.springframework.data.cassandra.repository.query.CassandraQueryMethod.(CassandraQueryMethod.java:68)

    Please help.

    ReplyDelete
    Replies
    1. The argument for the save method should be class which is annotated with @Table

      Delete
  2. What is sampleRepository.save(sample, ttl);
    in your case?
    Ho do you get sample repository from RepositoryFactorySupport?
    Could you describe in details ?

    ReplyDelete
  3. MyRepositoryFactoryBean is specified in @EnableCassandraRepositories annotations. Spring takes care of initating and creating the repository beans. You just need to autowire them. I updated the post to show how to use SampleRepository.

    ReplyDelete
  4. great article!!!!!This is very importent information for us.I like all content and information.I have read it.You know more about this please visit again.

    Cassandra Training in Chennai

    ReplyDelete