【问题标题】:Save date in cassandra with spring用春天在 cassandra 中保存日期
【发布时间】:2021-01-18 08:12:20
【问题描述】:

我正在尝试通过 spring 将日期自动保存在 cassandra 中,为此我将使用 spring (Date) 获得的日期类型更改为 Cassandra (Date yyyy-mm-dd) 的格式

控制器

@PostMapping("/add")
public ResponseEntity<Cliente> crearCliente(@RequestBody Cliente cliente) {
    Date fecha = new Date();
    System.out.println(fecha);
    long lnMilisegundos = fecha.getTime();
    java.sql.Date sqlDate = new java.sql.Date(lnMilisegundos);

    cliente.setCreateAt(sqlDate);
    cliente.setUpdateAt(sqlDate);

    return clienteSevicio.crearCliente(cliente);
}

服务

@Override
public ResponseEntity<Cliente> crearCliente(Cliente cliente) {
    try {
        System.out.println(((Object)cliente.getCreateAt()).getClass().getSimpleName());
        System.out.println(cliente.getCreateAt());
        Cliente _cliente = clienteRepositorio.save(new Cliente(UUIDs.timeBased(), cliente.getNombre(), cliente.getApellido(), cliente.getEmail(), cliente.getCreateAt(), cliente.getUpdateAt()));
        return new ResponseEntity<>(_cliente, HttpStatus.CREATED);
    }catch (Exception e ) {
        System.out.printf("Error");
        System.out.println(e);
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

我正在通过控制台打印数据类型和数据(日期)以查看它们是否正确并打印以下内容:日期 2020-10-02

但它也向我打印错误:

Errororg.springframework.data.cassandra.CassandraInvalidQueryException: SessionCallback; CQL [INSERT INTO clientes (apellido,create_at,email,id,nombre,update_at) VALUES ('string',1601646868204,'string3',c9ee78e0-04b6-11eb-bfa7-39627886e1eb,'string2',1601646868204);]; Expected 4 byte long for date (8); nested exception is com.datastax.driver.core.exceptions.InvalidQueryException: Expected 4 byte long for date (8)

看到错误,它向我传递了日期“1601646868204”,而它应该是“2020-10-02”,为什么会这样?我做错了什么?

【问题讨论】:

  • 尝试使用 com.datastax.driver.core.LocalDate 而不是 java.sql.Date

标签: spring date cassandra


【解决方案1】:

基本上,当您定义时:

long lnMilisegundos = fecha.getTime();
java.sql.Date sqlDate = new java.sql.Date(lnMilisegundos);

将存储在 sqlDate 变量中的值是与您正在使用的日期相关的毫秒数。 根据java.sql.Date定义:

一个毫秒值的瘦包装器,允许 JDBC 将其识别为 SQL DATE 值。毫秒值表示自 1970 年 1 月 1 日 00:00:00.000 GMT 以来经过的毫秒数。

您需要使用其他类型或将毫秒变量格式化为 YYYY-MM-DD(年-月-日)

【讨论】:

    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2022-01-19
    • 2020-01-09
    • 2016-08-05
    • 1970-01-01
    • 2017-02-17
    • 2012-10-27
    • 2016-11-29
    相关资源
    最近更新 更多