如何实现java时间LocalDate到数据税LocalDate的Cassandra转换器



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

List listOfStudents=findStudentByStudentNumber((;

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

有几个选项。

也许最简单的是通过年、月和日进行转换:

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()));

代码尚未编译。请原谅任何拼写错误。

链接:com.datastax.driver.core.LocalDate文档

最新更新