Search code examples
javaspring-bootcassandradatastaxdatastax-java-driver

Unable to retrieve the data from datastax having timestamp field


I'm having the below table in the keyspace myks

CREATE table IF NOT EXISTS myks.users (
    user_name text,
    email text,
    created_at timestamp,
    updated_at timestamp,
    PRIMARY KEY (user_name)
);

Below is the model class

@Table(value = "users")
public @Data class Users{
    @PrimaryKey
    @Column("user_name")
    @CassandraType(type = DataType.Name.TEXT)
    private String user_name;

    @Column("email")
    @CassandraType(type = DataType.Name.TEXT)
    private String email;

    @Column("created_at")
    @CassandraType(type = DataType.Name.TIMESTAMP)
    private Timestamp created_at;

    @Column("updated_at")
    @CassandraType(type = DataType.Name.TIMESTAMP)
    private Timestamp updated_at;
}

Repository interface

@Repository
public interface UsersRepository extends CrudRepository<Users, String> {
}

Inserted the below values into the table

Users users = new Users();
LocalDateTime ldt_created = LocalDateTime.now();
LocalDateTime ldt_updated = ldt_created.plus(1000, ChronoUnit.MILLIS);
Timestamp ts_created = Timestamp.valueOf(ldt_created);
Timestamp ts_updated = Timestamp.valueOf(ldt_updated);
users.setUser_name(krishna");
users.setEmail("[email protected]");
users.setCreated_at(ts_created);
users.setUpdated_at(ts_updated);
usersRepository.save(users);

It got saved in the table but while retrieving the data it is throwing the below exception

No converter found capable of converting from type [java.util.Date] to type [java.sql.Timestamp]

Solution

  • CQL's timestamp type is mapped into java.util.Date Java type, so you need to use it instead of Timestamp. See CQL to Java mapping table for this & other types.

    You can also use so-called optional codecs (an additional dependency) to map timestamp into other Java types, such as, Instant. See documentation for more information.