-
mongodb의 @Indexed 가 작동하지 않을 때프레임워크/Spring Boot 2023. 12. 24. 16:41
Entity에 @Indexed 어노테이션이 작동하지 않는 이슈를 해결하는 과정입니다.
아래는 Spring에서 선언한 Entity입니다.
productId에 @Indexed(unique = true) 를 적용했음에도 DuplecateKeyError가 발생하지 않았습니다
@Document(collection="products") public class ProductEntity { @Id private String id; @Version private Integer version; @Indexed(unique = true) private int productId;
확인해보니 mongodb에 인덱스가 설정되지 있지 않았습니다
공식문서를 확인해보면 3.0 버전부터 의도하지 않은 impact를 방지하기 위해 명시적으로 선언하는 것으로 변경되었다고 안내하고 있습니다.
Entity 선언 시에 @Indexed 어노테이션이 작동하지 않는 경우에는 추가적으로 인덱스 자동생성 항목을 true로 선언해주어야 합니다.
문서의 예제에는 서버 실행 후에 인덱스를 설정하는 예제들과 자동으로 true 처리하는 방법을 설명하고 있습니다.
@Configuration public class Config extends AbstractMongoClientConfiguration { @Override public boolean autoIndexCreation() { return true; } // ... }
config를 통해서 설정을 해주거나 yml 파일을 이용해서 간단하게 설정해줄 수 있습니다.
책의 예제를 따라하다 만난 경우인만큼 간단하게 yml 파일을 사용해서 설정해보록 하겠습니다.
spring: data: mongodb: auto-index-creation: true
yml 변경 후 재시작 해주면 index가 생성되는 것을 확인할 수 있습니다
[출처]
[이미지 출처]
'프레임워크 > Spring Boot' 카테고리의 다른 글
데이터베이스를 기반으로 JPA의 연관관계 살펴보기 <1> (0) 2024.02.06 Entity의 Id 생성 전략에 따른 EntityManager의 persist 동작 확인 (0) 2024.02.06 Spring boot 2.7.18에서 swagger 설정하기 <2> (0) 2024.01.23 Spring boot 2.7.18에서 swagger 설정하기 <1> (0) 2024.01.22 Junit5 에서 Junit4로 변경하기 (0) 2023.12.24