본문 바로가기

MongoDB

SpringBoot 에서 MongoDB 사용

728x90
반응형

SpringBoot 에서 MongoDB 사용

MongoDB 공식 튜토리얼

  • CRUD 예제

Spring Boot Integration With MongoDB Tutorial

  • mongoDB RestfulAPI 튜토리얼
  • mongodb java 튜토리얼( 매핑하는 법)

Java - Mapping POJOs | MongoDB

예제 스터디

Spring Boot Integration With MongoDB Tutorial

  • 공식 사이트에서 예제는 maven기반이다. 하지만 나의 프로젝트는 gradle이어서 gradle로 변환하면서 생각했다.

1.의존성

  • spring-boot-starter-data-mongodb 가 mongodb 의존성이다.
  • build.gradle 에서 implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' 로 변환하면 될 듯하다.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

      ...
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    ...

    </dependencies>
      ...

</project>

엔티티 정의

  • 상품 엔티티이다.
  • @Document("groceryitems")
  • @Id
  • 생성자까지 기존과 거의 비슷하다.
@Document("groceryitems")
public class GroceryItem {

        @Id
        private String id;

        private String name;
        private int quantity;
        private String category;

        public GroceryItem(String id, String name, int quantity, String category) {
            super();
            this.id = id;
            this.name = name;
            this.quantity = quantity;
            this.category = category;
        }
}

Repository

예제에서는 이름으로 검색, 카테고리로 전체 검색이 있다.

기존의 springdataJpa 와 문법이나 사용구조가 비슷하다.

  • springdataJpa 처럼 MongRepository<엔티티, 기본키 자료형> 를 상속받으면 바로 쓸 수 있는 구조같다.
  • @Query(”{}”) : 어노테이션으로 쿼리문을 작성한다.
public interface ItemRepository extends MongoRepository<GroceryItem, String> {

    @Query("{name:'?0'}")
    GroceryItem findItemByName(String name);

    @Query(value="{category:'?0'}", fields="{'name' : 1, 'quantity' : 1}")
    List<GroceryItem> findAll(String category);

    public long count();

}

applicaion.yml

  • yml 설정으로 외부 몽고디비 데이터베이스와 연결한다.
spring.data.mongodb.uri=mongodb+srv://<username>:<pwd>@<cluster>.mongodb.net/mygrocerylist
spring.data.mongodb.database=mygrocerylist

Application 실행 파일

@SpringBootApplication
@EnableMongoRepositories
public class MdbSpringBootApplication implements CommandLineRunner{

    @Autowired
    ItemRepository groceryItemRepo;

    public static void main(String[] args) {
        SpringApplication.run(MdbSpringBootApplication.class, args);
    }

CRUD 예제

  • Service 에 해당하는 코드로 보면 될 듯하다.

생성

//CREATE
    void createGroceryItems() {
        System.out.println("Data creation started...");
        groceryItemRepo.save(new GroceryItem("Whole Wheat Biscuit", "Whole Wheat Biscuit", 5, "snacks"));
        groceryItemRepo.save(new GroceryItem("Kodo Millet", "XYZ Kodo Millet healthy", 2, "millets"));
        groceryItemRepo.save(new GroceryItem("Dried Red Chilli", "Dried Whole Red Chilli", 2, "spices"));
        groceryItemRepo.save(new GroceryItem("Pearl Millet", "Healthy Pearl Millet", 1, "millets"));
        groceryItemRepo.save(new GroceryItem("Cheese Crackers", "Bonny Cheese Crackers Plain", 6, "snacks"));
        System.out.println("Data creation complete...");
    }

조회

// READ
    // 1. Show all the data
     public void showAllGroceryItems() {

         groceryItemRepo.findAll().forEach(item -> System.out.println(getItemDetails(item)));
     }

     // 2. Get item by name
     public void getGroceryItemByName(String name) {
         System.out.println("Getting item by name: " + name);
         GroceryItem item = groceryItemRepo.findItemByName(name);
         System.out.println(getItemDetails(item));
     }

     // 3. Get name and quantity of a all items of a particular category
     public void getItemsByCategory(String category) {
         System.out.println("Getting items for the category " + category);
         List<GroceryItem> list = groceryItemRepo.findAll(category);

         list.forEach(item -> System.out.println("Name: " + item.getName() + ", Quantity: " + item.getQuantity()));
     }

     // 4. Get count of documents in the collection
     public void findCountOfGroceryItems() {
         long count = groceryItemRepo.count();
         System.out.println("Number of documents in the collection: " + count);
     }

수정

public void updateCategoryName(String category) {

         // Change to this new value
         String newCategory = "munchies";

         // Find all the items with the category snacks
         List<GroceryItem> list = groceryItemRepo.findAll(category);

         list.forEach(item -> {
             // Update the category in each document
             item.setCategory(newCategory);
         });

         // Save all the items in database
         List<GroceryItem> itemsUpdated = groceryItemRepo.saveAll(list);

         if(itemsUpdated != null)
             System.out.println("Successfully updated " + itemsUpdated.size() + " items.");         
     }

삭제

// DELETE
     public void deleteGroceryItem(String id) {
         groceryItemRepo.deleteById(id);
         System.out.println("Item with id " + id + " deleted...");
     }

MongoDB Repository 커스터마이징

리파지토리 인터페이스를 상속받아 자신이 원하는 데로 커스터마이징 할 수 있다.

[인터페이스]

public interface CustomItemRepository {

    void updateItemQuantity(String name, float newQuantity);

}

[커스터마이징 구현 리포지토리]

@Component
public class CustomItemRepositoryImpl implements CustomItemRepository {

    @Autowired
    MongoTemplate mongoTemplate;

    public void updateItemQuantity(String name, float newQuantity) {
        Query query = new Query(Criteria.where("name").is(name));
        Update update = new Update();
        update.set("quantity", newQuantity);

        UpdateResult result = mongoTemplate.updateFirst(query, update, GroceryItem.class);

        if(result == null)
            System.out.println("No documents updated");
        else
            System.out.println(result.getModifiedCount() + " document(s) updated..");

    }

}

[Service]

@Autowired
    CustomItemRepository customRepo;

// UPDATE
     public void updateItemQuantity(String name, float newQuantity) {
         System.out.println("Updating quantity for " + name);
         customRepo.updateItemQuantity(name, newQuantity);
     }
반응형