SpringBoot下实现MongoDB字段类型转换器

1 目的

MongoDBJava
StringLocalDateTime

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

转载于:https://www.cnblogs.com/linzhanfly/p/9578738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值