Back-End/Spring

[spring] SpringBoot mongodb 인덱싱 안되는 문제 (SpringBoot mongodb Unique index not created)

Henu 2022. 5. 11. 00:49

embedded mongodb를 사용해 테스트를 진행했다.

인덱스가 중복되는 Entity를 저장하려 할 경우에 DuplicateKeyException 에러를 던질 줄 알았지만..

 

아무일도 일어나지 않았다.

 

@Document(collection = "products")
@NoArgsConstructor
@Getter
@Setter
public class ProductEntity {

    @Id
    private String id;

    @Version
    private Integer version;

    @Indexed(unique = true)
    private int productId;
    
    ...
}

테스트에 사용중인 Entity의 일부이다.

 

productId@Indexed 어노테이션을 unique = true 로 걸어주었다.

 

이렇게 설정하면 productId를 기준으로 indexing 테이블이 생성되고 중복된 productId를 가진 Entity의 생성을 금지한다.

 

 

하지만 중복된 productId를 가진 객체가 잘 저장되는 상황이었다.

 

아무리 봐도 Mongodb에서 index가 잘 생성되지 않는 것 같아서 마구 구글링을 한 결과 답을 찾았다😁

 

https://docs.spring.io/spring-data/mongodb/docs/current-SNAPSHOT/reference/html/#new-features.3.0

2번째 설명을 보면 기본 설정으로 Auto-index creation이 disable 되었다고 한다.

 

좀 더 타고 들어가면

https://docs.spring.io/spring-data/mongodb/docs/current-SNAPSHOT/reference/html/#mapping.index-creation

mongodb 3.0 이후부터 컬렉션 라이프 사이클과 퍼포먼스에 영향을 주는 것을 막기 위해서 Index creation을 반드시 명시적으로 enable 해주어야 한다고 한다.

 

 

명시적으로 enable 해주기 위해서는 아래와 같이 application.yml 을 설정한다.

// application.yml

spring:
  data:
    mongodb:
      auto-index-creation: true

 

 

참조

 

MongoDB unique index not created In spring boot

In a Spring boot + MongoDB application, I'm trying to create an unique index for an email field. @Document public class User { @Id private String id; @Indexed(unique = true) pri...

stackoverflow.com