Spring Data MongoDB with Java 8 LocalDate MappingException

后端 未结 3 1816
醉酒成梦
醉酒成梦 2020-12-06 17:45

I try to use the LocalTime from Java 8 Date Time API with Spring Data MongoDB. Inserting the document works as expected, but when I try to read the document, I get the follo

相关标签:
3条回答
  • 2020-12-06 18:01

    I wrote this little bit of code for all 4 of these conversion options:

    • DateToLocalDateTimeConverter
    • DateToLocalDateConverter
    • LocalDateTimeToDateConverter
    • LocalDateToDateConverter

    Here is an example

    public class DateToLocalDateTimeConverter implements Converter<Date, LocalDateTime> {
    
        @Override 
        public LocalDateTime convert(Date source) { 
            return source == null ? null : LocalDateTime.ofInstant(source.toInstant(), ZoneId.systemDefault()); 
        }
    }
    

    All example here.

    Then by including this in the xml configuration for the mongodb connection I was able to work in java 8 dates with mongodb (remember to add all the converters):

    <mongo:mapping-converter>
        <mongo:custom-converters>
            <mongo:converter>
                <bean class="package.DateToLocalDateTimeConverter" />
            </mongo:converter>
        </mongo:custom-converters>
    </mongo:mapping-converter>
    
    0 讨论(0)
  • 2020-12-06 18:15

    Now problem is resolved: https://jira.spring.io/browse/DATAMONGO-1102

    But Spring Data doesn't support ZonedDateTime now, only Local.

    0 讨论(0)
  • 2020-12-06 18:15

    This is currently not supported mostly due to the fact that MongoDB doesn't support storing Java 8 date time types right now. I suggest to turn the internal property into a legacy Date one and do the conversions on the API of the domain class (as you would do with Hibernate and JodaTime e.g.).

    0 讨论(0)
提交回复
热议问题