Spring数据MongoDB示例不起作用

时间:2012-03-23 16:00:19

标签: spring mongodb spring-data

我只是想从reference doc工作中获取“向所有存储库添加自定义行为”示例。但对于以下课程:

public class MyRepositoryImpl<T, ID extends Serializable>
  extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> {

  public void sharedCustomMethod(ID id) {
    // implementation goes here
  }
}

我收到编译错误

  

没有为SimpleJpaRepository()找到合适的构造函数   构造函数org.springframework.data.jpa.repository.support.SimpleJpaRepository.SimpleJpaRepository(java.lang.Class,javax.persistence.EntityManager)不适用
  (实际和正式的参数列表长度不同)
  构造函数org.springframework.data.jpa.repository.support.SimpleJpaRepository.SimpleJpaRepository(org.springframework.data.jpa.repository.support.JpaEntityInformation,javax.persistence.EntityManager)不适用
  (实际和正式的参数列表长度不同)

我怎样才能使这个工作?

4 个答案:

答案 0 :(得分:0)

为所有存储库添加自定义行为的适当解决方案&#39;使用spring-data mongodb在此post中有详细说明。

按照上面的帖子中描述的步骤后,您可以使用任何存储库接口来扩展custom-shared-repository-interface,如下所示

@Repository
public interface CustomerRepository extends MongoRepository<Customer, String>,
        WootideRepositoryCustom<Customer, String> {
}

WootideRepositoryImpl中提供的实现将在CustomerRepository中提供。

对我来说效果很好。

希望更新spring数据mongodb doc,因为它是第一个参考位置。

答案 1 :(得分:0)

我不咸,但遗憾的是,实施这一点并不清楚。

查看图片以获取完整示例,github: https://github.com/mpereira-dev/spring-data-mongo-shared-repo-example

关键点:

  1. 您必须在基接口上使用 @NoRepositoryBean ,因此Spring不会为它创建一个bean。
  2. 基本界面的名称与将自定义方法添加到单个仓库无关。
  3. 实施类的名称也无关紧要
  4. @Repository 添加到实现类将产生以下错误:
  5.   

    构造函数的参数0   com.example.demo.repository.ImplementationRepoNameDoesntMatterEitherUnlikeAddingCustomMethodsToSingleRepo   需要一个类型的bean   'org.springframework.data.mongodb.repository.query.MongoEntityInformation'   无法找到。

    1. 您必须使用:
    2.   

      @EnableMongoRepositories(   repositoryBaseClass = ImplementationRepoNameDoesntMatterEitherUnlikeAddingCustomMethodsToSingleRepo.class)

      告诉spring你的基类如果不这样你会得到这个错误(spring尝试将方法解析为查询):

        

      引起:   org.springframework.data.mapping.PropertyReferenceException:没有   找到类型为Person的someMethod属性!

      1. 确保您的包结构符合弹簧约定,因此所有组件都可以通过spring发现,其他方面可以配置有趣的组件:@ ComponentScan,@ EntityScan和@EnableMongoRepositories。
      2. A picture says a thousand words

        7.6.2。向所有存储库添加自定义行为

        https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories

答案 2 :(得分:-1)

首先,这是一个简单的编译错误,因为超类有一个构造函数,你必须复制或提供一个自己的构造函数。其次,您似乎正在混淆它的JPA和MongoDB模块。您宁愿扩展SimpleMongoRepository

答案 3 :(得分:-1)

@Oliver所说的是您错误地复制/粘贴了代码。 Spring-Data-MongoDB Docs复制/粘贴了来自Spring-Data-JPA Docs的代码,但忘了更改它。如果你真的看看你的代码,那么变化很简单。

public interface MyMongoRepository<T, ID extends Serializable> extends MongoRepository<T, ID> {

    void sharedCustomMethod(ID id);
}


public class MyImplMongoRepository<T, ID extends Serializable> extends SimpleMongoRepository<T, ID> implements MyMongoRepository<T, ID> {

    public void sharedCustomMethod(ID id) {
        // implementation goes here
    }
}

这清楚了吗?这只是文档中的一个错字。