Spring에서 MongoDB 사용하기

코딩베어 ㅣ 2020. 2. 19. 18:37

728x90

Repository를 MongoDB의 MongoTemplete을 사용하여 구현

먼저 MongoDB를 사용하기 위해 의존성을 추가한다.

<dependency>
	<groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
</dependency>

 

MongoDB의 _id필드는 id에 자동으로 매핑된다. 식별자를 별도로 지정하고 싶다면 @Id 애노테이션을 사용한다.

MongoRepository 사용하기

public interface ItemRepository extends MongoRepository<Item, String>{}

JPA와 비슷하게 사용한다.

ReactiveMongoRepository 사용하기

public interface ItemRepository extends ReactiveMongoRepository<Item, String>{}

반응형으로 사용하려면 ReactiveMongoRepository를 사용한다. 또, subscribe 메서드를 사용해야한다.

MongoRepository 테스트하기

내장 MongoDB 사용 시 @Test대신 @MongoRepositoryTest 애노테이션을 사용하여 간단하게 테스트 코드를 작성할 수 있다.

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#reference

 

Spring Data MongoDB - Reference Documentation

As of version 3.6, MongoDB supports the concept of sessions. The use of sessions enables MongoDB’s Causal Consistency model, which guarantees running operations in an order that respects their causal relationships. Those are split into ServerSession instan

docs.spring.io

728x90