zoukankan      html  css  js  c++  java
  • SpringBoot下实现MongoDB字段类型转换器

    1 目的

    MongoDB Java
    String LocalDateTime

    2 实现

    • 先定义实体类
    @Data // lombok
    @Accessors(chain = true)
    @Document(collection = "UserEntity")
    public class User implements Serializable {
        @Id
        private String id;
        private String username;
        private String password;
        // java中为LocalDateTime,根据Spring Data MongoDB的介绍:
        // LocalDateTime -> MongoDB的{"date" : ISODate("2019-11-12T23:00:00.809Z")}
        private LocalDateTime birthDay;
    }
    
    • 定义Repository
    public interface UserRepository extends MongoRepository<UserEntity, String>{
    }
    
    • 定义转换器
    // Direction: Java -> MongoDB
    @WritingConverter 
    public class DateToString implements Converter<LocalDateTime, String> {
        @Override
        public String convert(LocalDateTime source) {
            return source.toString() + 'Z';
        }
    }
    
    // Direction: MongoDB -> Java
    @ReadingConverter 
    public class StringToDate implements Converter<String, LocalDateTime> {
        @Override
        public LocalDateTime convert(String source) {
            return LocalDateTime.parse(source,DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
        }
    }
    
    • 注册转换器
    @Configuration
    public class MongoConfig {
        @Bean
        public CustomConversions customConversions() {
            List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
            converterList.add(new DateToString());
            converterList.add(new StringToDate());
            return new CustomConversions(converterList);
        }
    }
    
    • 最后测试
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserDaoTest {
        @Autowired
        private UserRepository userRepository;
        
        @Test
        public void testSaveUser() {
            UserEntity user = new UserEntity();
            user.setUserName("test");
            user.setPassWord("test");
            user.setBirthDay(LocalDateTime.now());
            userRepository.saveUser(user);
        }
    }
    

    3 字符串的日期怎么区间查询?

    public interface UserRepository extends MongoRepository<UserEntity, String>{
    	List<UserEntity> findByBirthDayBetween(LocalDateTime start, LocalDateTime end);
    }
    
  • 相关阅读:
    错误总结Mapper扫描不到
    Spring项目出现--Error:java: Compilation failed: internal java compiler error
    mybatis-plus自动填充时间
    自定义异常类
    Swagger配置类
    JwtUtils工具类
    MD5加密工具类
    SpringBoot通用返回JSON数据封装类
    使用Swagger测试使传入json数据时出现JSON parse error: Unexpected character (‘}‘ (code 125)): was expecting double
    org.springframework.context.ApplicationContextException: Unable to start web server; nested exceptio
  • 原文地址:https://www.cnblogs.com/linzhanfly/p/9578738.html
Copyright © 2011-2022 走看看