부트 개념과 활용-28.MongoDB(스프링 데이터)
스프링 데이터 10부: MongoDB
MongoDB는 JSON 기반의 도큐먼트 데이터베이스
의존성 추가
<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 -i -t mongo_boot bash
- mongo
스프링 데이터 몽고DB
- MongoTemplate
- MongoRepository
실습 코드
@SpringBootApplication
public class RedisApplication {
@Autowired
MongoTemplate mongoTemplate;
@Autowired
AccountRepository accountRepository;
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
@Bean
public ApplicationRunner applicationRunner(){
return args -> {
Account account = new Account();
account.setEmail("2-jaeuk2274@gamil.com");
account.setUsername("2-jaeuk");
//mongoTemplate.insert(account);
accountRepository.insert(account); // 둘 다 사용가능
System.out.println("finished");
};
}
}
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "accounts") // 컬렉션이 RDBMS로 치면 테이블
public class Account {
@Id
private String id;
private String username;
private String email;
...
public interface AccountRepository extends MongoRepository<Account, String> {
}
16:51:31 jaeuk@JUui-MacBook-Pro15 ~ 26s
$ docker exec -i -t mongo_boot bash
root@ef2481d704bd:/# mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("00046247-3197-4494-9ad8-463f91a6a83e") }
MongoDB server version: 4.2.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2019-12-24T07:51:31.363+0000 I STORAGE [initandlisten]
2019-12-24T07:51:31.363+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-12-24T07:51:31.364+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2019-12-24T07:51:31.911+0000 I CONTROL [initandlisten]
2019-12-24T07:51:31.911+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-12-24T07:51:31.911+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2019-12-24T07:51:31.911+0000 I CONTROL [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).
The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.
To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> db
test
> use test
switched to db test
> db.accounts.find({})
> db.accounts.find({})
{ "_id" : ObjectId("5e01c42e9a098d02a39e2cbd"), "username" : "jaeuk", "email" : "jaeuk2274@gamil.com", "_class" : "me.jaeuk.redis.account.Account" }
> db.accounts.find({})
{ "_id" : ObjectId("5e01c42e9a098d02a39e2cbd"), "username" : "jaeuk", "email" : "jaeuk2274@gamil.com", "_class" : "me.jaeuk.redis.account.Account" }
{ "_id" : ObjectId("5e01c4a9b05cbb380f6d96aa"), "username" : "2-jaeuk", "email" : "2-jaeuk2274@gamil.com", "_class" : "me.jaeuk.redis.account.Account" }
>
내장형 MongoDB (테스트용)
- de.flapdoodle.embed:de.flapdoodle.embed.mongo
- @DataMongoTest
실습 코드(테스트)
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
@ExtendWith(SpringExtension.class)
@DataMongoTest
class AccountRepositoryTest {
// 테스트용 db를 바라보게 할 수도 있지만 내장형 mongoDB 지원 // 의존성추가
@Autowired
AccountRepository accountRepository;
@Test
public void findByEmail(){
Account account = new Account();
account.setUsername("jaeuk");
account.setEmail("jaeuk2274@gmail.com");
accountRepository.save(account);
Optional<Account> byId = accountRepository.findById(account.getId());
assertNotNull(byId, "byId not null");
Optional<Account> byEmail = accountRepository.findByEmail(account.getEmail());
assertNotNull(byEmail, "byEmail not null");
assertEquals("jaeuk", byEmail.get().getUsername());
}
}