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);
}
posted @ 2018-09-03 15:22  月下小魔王  阅读(8998)  评论(0编辑  收藏  举报