[스프링 부트] chapter 34. 스프링 데이터 10부 MongoDB
스프링 데이터 10부 MongoDB
의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
MongoDB 설치 및 실행 (도커)
- docker run -p 27017:27017 –name mongo_boot -d mongo
- docker exec -it mongo_boot bash
- mongo
스프링 데이터 몽고DB
-
MongoTemplate
@Document(collection = "accounts") public class Account { @Id private String id; private String username; private String email; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
@SpringBootApplication public class SpringbootmongoApplication { @Autowired MongoTemplate mongoTemplate; public static void main(String[] args) { SpringApplication.run(SpringbootmongoApplication.class, args); } @Bean public ApplicationRunner applicationRunner() { return args -> { Account account = new Account(); account.setEmail("juho@mail.com"); account.setUsername("juho"); mongoTemplate.insert(account); } } }
-
MongoRepository
(예제는 아래 @DataMongoTest 참조)
-
내장형 MongoDB (테스트용)
-
의존성 추가
<dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> <scope>test</scope> </dependency>
-
-
@DataMongoTest
-
예제 소스
@RunWith(SpringRunner.class) @DataMongoTest public class AccountRepositoryTest { @Autowired AccountRepository accountRepository; @Test public void findByEmail() { Account account = new Account(); account.setUsername("Juho"); account.setEmail("juho@mail.com"); accountRepository.save(account); Optional<Account> byId = accountRepository.findById(account.getId()); assertThat(byId).isNotEmpty(); Optional<Account> byEmail = accountRepository.findByEmail(account.getEmail()); assertThat(byEmail).isNotEmpty(); assertThat(byEmail.get().getUsername()).isEqualTo("Juho"); } }
-