이전글
https://geonbbang.tistory.com/25
[MongoDB] 데이터베이스 연동하기(1)
데이터베이스 설치 및 사용 준비1. ec2에 MongoDB를 설치 후 실행1. /etc/yum.repos.d/mongodb-org-6.0.repo파일 생성 후 밑의 설정 입력 후 저장[mongodb-org-6.0]name=MongoDB Repositorybaseurl=https://repo.mongodb.org/yum/amazon/2
geonbbang.tistory.com
프로젝트와 MongoDB 연결
1. Dependency 설정
implementation ("org.springframework.boot:spring-boot-starter-data-mongodb")
2. MongoDB 연결 정보 등록 (application.yml)
인증을 이용하는 경우 다음 정보를 추가해준다. (이전 게시글에서 어드민 계정을 생성한 데이터베이스이다)
authentication-database: "admin" // 해당 인증을 처리하기 위한 데이터베이스
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#data.nosql.mongodb
Spring Boot Reference Documentation
This section goes into more detail about how you should use Spring Boot. It covers topics such as build systems, auto-configuration, and how to run your applications. We also cover some Spring Boot best practices. Although there is nothing particularly spe
docs.spring.io
연결 테스트
1. Document 생성
다음과 같이 Example.kt 파일을 생성한다.
import org.springframework.data.mongodb.core.mapping.Document
import javax.persistence.Id
@Document(collection = "examples")
class Example (
@Id
var id: String,
var title: String,
var year: Number,
)
2. Repository 생성
다음과 같이 ExampleRepository.kt 파일을 생성한다.
import org.springframework.data.mongodb.repository.MongoRepository
interface ExampleRepository : MongoRepository<Example, String> {}
3. Controller 생성
다음과 같이 ExampleController.kt 파일을 생성한다.
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class ExampleController (private val exampleRepository: ExampleRepository) {
@GetMapping("/")
fun hi(): String {
return "hi"
}
@GetMapping("/examples")
fun examples(): MutableList<Example> {
return exampleRepository.findAll();
}
}
4. Postman등을 이용하여 다음과 같이 데이터를 잘 가져오는지 확인한다.
[
{
"id": "640ed612de13b7a18e81f244",
"title": "aaaa",
"year": 2021
}
]
'Database' 카테고리의 다른 글
| Redis(2) (0) | 2023.06.11 |
|---|---|
| Redis(1) (0) | 2023.06.07 |
| [MongoDB] 데이터베이스 연동하기(1) (0) | 2023.03.13 |
| TIL. 인덱스(INDEX) (0) | 2023.02.09 |
| SQL VS NoSQL (0) | 2023.02.08 |