티스토리 뷰

Developer

MongoDB with SpringData

rocksea 2021. 1. 8. 14:55

MongoDB를 제어하기 위한 MongoTemplate과 MongoRepository 차이점과 사용방법에 대해 기술한다.

MongoTemplate과 MongoRepository의 차이


이 두가지 방식은 약간 상반되는 목표를 가진다.

편리함(Convenient)

  • MongoRepository
    • 간단한 CRUD를 처리할때 용이하며 간단한 만큼 세세한 제어가 불가능하다.
    • CRUD 및 find 메서드, sort와 pagnation에 대한 동적인 Query Derivation 기능이 제공

강력한 사용성(powerful to use)

  • MongoTemplete
    • 복잡한 수준의 쿼리에 대한 제어가 가능함.
    • Repository보다 복잡한 제어가 가능하지만 직접 제어기능을 구현해야하는 번거로움이 있다.

위 두가지 기능을 적절히 조합하여 사용하기 위해 CostomizedRepository를 사용하도록 한다.

Customized Repository 구현 방법


Query Method에 다른 동작이 정의되어야 하거나 Query Derivation 만으로 구현할 수 없는 경우 Spring Data Repository의 custom implmentations을 통해 custom repository code와 기본 CRUD 추상화 쿼리 메서드를 함께 제공할 수 있다.

1. Customized repository 생성

interface CustomizedUserRepository {
  void customizedMethod(User user);
}

 

2. Customized Interface에 대한 구현 클래스를 생성

class UserRepositoryImpl implements CustomizedUserRepository {

  private final MongoOperations operations;

  @Autowired
  public UserRepositoryImpl(MongoOperations operations) {

    Assert.notNull(operations, "MongoOperations must not be null!");
    this.operations = operations;
  }

  public List<User> customizedMethod() {
    // custom implementation here
  }
}

 

3. Customized Repository 상속

끝으로 CrudRepository와 Customized Interface를 함께 상속하여 사용할 수 있다.

interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {

}

 

References


stackoverflow.com/questions/17008947/whats-the-difference-between-spring-datas-mongotemplate-and-mongorepository

'Developer' 카테고리의 다른 글

Infrastructure as Code with Terraform  (0) 2021.07.22
ElastiCache with SpringData  (0) 2021.05.21
[OpenJDK] How to install OpenJDK  (0) 2020.10.20
How to create VPC for HA(High Availability) on AWS  (0) 2020.09.02
How to use ElasticBeanstalk  (0) 2020.08.12
댓글