【问题标题】:How to implement Cassandra converter for java time LocalDate to datastax LocalDate?java - 如何将Java时间LocalDate的Cassandra转换器实现为datastax LocalDate?
【发布时间】:2022-01-02 07:01:03
【问题描述】:

我有一个 spring data cassandra 查询,它以 java.time.LocalDate 格式获取本地日期值,我需要将此值转换为 cassandra 配置 bean 中的 com.datastax.driver.core.LocalDate。如何实施? 示例:

列出listOfStudents = findStudentByStudentNumber();

这里,findStudentByStudentNumber() 以 java.time.LocalDate 格式获取日期,但 List 具有 com.datastax.driver.core.LocalDate 格式。我需要在 @Configuration 类中定义一个 @Bean 来自动转换它。最好的方法是什么?

【问题讨论】:

    标签: spring-boot cassandra datastax-java-driver localdate spring-data-cassandra


    【解决方案1】:

    有几个选项。

    也许最直接的方法是通过年、月和日进行转换:

        java.time.LocalDate javaDate = // …;
        com.datastax.driver.core.LocalDate staxDate
                = com.datastax.driver.core.LocalDate.fromYearMonthDay(
                        javaDate.getYear(), javaDate.getMonthValue(), javaDate.getDayOfMonth());
    

    这有效,因为 java.time 和 Datastax 都从 1 开始编号。

    有点短,没有交换参数的风险,所以可能是我的偏好:

        com.datastax.driver.core.LocalDate staxDate
                = com.datastax.driver.core.LocalDate.fromDaysSinceEpoch(
                        Math.toIntExact(javaDate.toEpochDay()));
    

    代码尚未编译。如有错别字请见谅。

    链接: Documentation of com.datastax.driver.core.LocalDate

    【讨论】:

      猜你喜欢
      • 2018-07-15
      • 2023-03-24
      • 2015-05-23
      • 2015-11-07
      • 2022-01-07
      • 1970-01-01
      • 2011-04-12
      • 2017-11-02
      • 2020-04-10
      相关资源
      最近更新 更多