Spring MongoDB 的自定义存储库

Spring custom repository for MingoDB

告诉我如何正确实施 mongodb 的存储库? 目前,使用此配置,由于某种原因我收到错误.... ((

@Configuration
@EnableMongoRepositories(basePackages = "by.repository.mongo", repositoryBaseClass = BaseMongoRepository.class)
public class MongoConfig {}

@NoRepositoryBean
public interface BaseMongoRepository<T extends BaseDocument> extends MongoRepository<T, String> {

  void saveCascade(T document);

}

public interface LimitRepository extends BaseMongoRepository<LimitDocument>, QuerydslPredicateExecutor<LimitDocument> {}

public class LimitRepositoryImpl extends BaseMongoRepositoryImpl<LimitDocument> implements BaseMongoRepository<LimitDocument> {

  public LimitRepositoryImpl(MongoEntityInformation<LimitDocument, String> metadata, MongoOperations mongoOperations) {
    super(metadata, mongoOperations);
  }

  @Override
  public void saveCascade(LimitDocument document) {
    save(document);
  }

描述:

by.repository.mongo.LimitRepositoryImpl 中构造函数的参数 0 需要找不到类型 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' 的 bean。

操作:

考虑在您的配置中定义类型为 'org.springframework.data.mongodb.repository.query.MongoEntityInformation' 的 bean。

更新 1

我找到了简单的解决方案... 但我想知道这样的决定是否有陷阱

public class LimitRepositoryImpl extends BaseMongoRepositoryImpl<LimitDocument> implements BaseMongoRepository<LimitDocument> {
...
  public LimitRepositoryImpl(MongoOperations mongoOperations) {
    super(getEntityInformationFor(LimitDocument.class, String.class), mongoOperations);
  }
...
  public static MongoEntityInformation getEntityInformationFor(Class clazz, Class idClazz) {
    TypeInformation typeInformation = ClassTypeInformation.from(clazz);
    MongoPersistentEntity mongoPersistentEntity = new BasicMongoPersistentEntity(typeInformation);
    return new MappingMongoEntityInformation(mongoPersistentEntity, idClazz);
  }
}

你可以用这个方法 Maven 依赖项:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
        <version>2.5.6</version>
</dependency>

存储库:

@Repository
public interface PersonRepository extends MongoRepository<PersonEntity, Integer>{}

而在你的主要 class:

@SpringBootApplication(scanBasePackages = {"com.example.data"})
@EnableMongoRepositories(basePackages = {"com.example.data"})
public class PersonApplication {
public static void main(String[] args) {
    SpringApplication.run(PersonApplication.class, args);
 }
}