Search code examples
javacassandradatastax-java-driver

How to get cql date in java?


I am using java8 and cassandra in my application. The datatype of current_date in cassandra table is 'date'. I am using entities in java to map to the table values. and the datatype in entity for the same field is java.sql.Date.

When I am trying to retrieve a record 'Select * from table where current_date='2017-06-06';' I am getting the following error'

`Caused by: com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: ['org.apache.cassandra.db.marshal.SimpleDateType' <-> java.sql.Date]

I have tried with various data types like :

com.datastax.driver.core.LocalDate, java.util.Date ,com.google.common.reflect.TypeToken

all are returning the same errors.

I have referred http://docs.datastax.com/en/developer/java-driver/3.1/manual/custom_codecs/extras/.

But I am stuck. Please help me out.


Solution

  • By default, Java driver will map date type into com.datastax.driver.core.LocalDate Java type.

    If you need to convert date to java.time.LocalDate, then you need to add extras to your project and either register codec globally as described in documentation:

    cluster.getConfiguration().getCodecRegistry()
         .register(LocalDateCodec.instance);
    

    Or you can specify codec for given column only:

    @Column(codec = LocalDateCodec.class)
    java.time.LocalDate date;
    

    Similarly, the conversion could be made into Joda time types.