SpringBoot에서 MongoDB 필드 형식 변환기 구현

2588 단어

1 목적


MongoDB
Java
String
LocalDateTime

이루다

  • 실체류를 먼저 정의
  • @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{
    }
  • 정의 변환기
  • // Direction: Java -> MongoDB
    @WritingConverter 
    public class DateToString implements Converter {
        @Override
        public String convert(LocalDateTime source) {
            return source.toString() + 'Z';
        }
    }
    
    // Direction: MongoDB -> Java
    @ReadingConverter 
    public class StringToDate implements Converter {
        @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> converterList = new ArrayList>();
            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{
        List findByBirthDayBetween(LocalDateTime start, LocalDateTime end);
    }

    전재 대상:https://www.cnblogs.com/linzhanfly/p/9578738.html

    좋은 웹페이지 즐겨찾기