1 目的
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;
}
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);
}