Spring Boot
[Spring Boot] Spring Boot와 MongoDB 연동하기
민이(MInE)
2023. 7. 19. 17:53
반응형
Spring Boot와 MongoDB를 연동하기에 앞서 MongoDB와 MongoDB Compass를 설치해줍니다!
의존성 추가
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
application.properties
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#spring.jpa.properties.hibernate.format_sql=true
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=toy
spring.data.mongodb.username=sodas
spring.data.mongodb.password=sodas1234
Model 생성
아래와 같이 작성하고 서버를 실행시키면 users라는 collection이 생성된다.
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document(collection = "users")
public class MongoDBTestModel {
private String id;
private String name;
private int age;
}
Repository 생성
import org.springframework.data.mongodb.repository.MongoRepository;
public interface MongoDBTestRepository extends MongoRepository<MongoDBTestModel, String> {
MongoDBTestModel findByName(String name);
}
Controller 생성
import com.example.toy.service.mongo.MongoDBTestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping(path = "/mongo")
public class MongoDBTestController {
@Autowired
MongoDBTestService mongoDBTestService;
@GetMapping(value = "/find")
public String findUserData(@RequestParam String name) {
return mongoDBTestService.selectUser(name);
}
@GetMapping(value = "/save")
public String saveUserData(@RequestParam String name, @RequestParam int age) {
log.info("[Controller][Recv] name : {}, age : {}", name, age);
mongoDBTestService.saveUser(name, age);
return mongoDBTestService.selectUser(name);
}
}
repository와 controller를 생성한 후 swagger를 통해 API 테스트를 해본다.
name과 age를 입력하고 Execute해주면 데이터가 잘 들어가 있는 것을 볼 수 있다!
반응형