4

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

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

4 回答 4

0

这篇文章详细介绍了使用 spring-data mongodb 为所有存储库添加自定义行为的适当解决方案。

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

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

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

对我来说效果很好。

希望 spring data mongodb doc 更新,因为它是第一个参考。

于 2014-09-26T07:32:34.630 回答
0

我不咸,但不幸的是,实现这一点根本不清楚。

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

关键点:

  1. 您必须在基本接口上使用@NoRepositoryBean,因此 spring 不会为其创建 bean。
  2. 基本接口的名称并不像将自定义方法添加到单个 repo 那样重要。
  3. 实现类的名称也无关紧要
  4. @Repository添加到实现类将产生以下错误:

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

  1. 您必须使用:

@EnableMongoRepositories(repositoryBaseClass = ImplementationRepoNameDoesntMatterEitherUnlikeAddingCustomMethodsToSingleRepo.class)

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

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

  1. 确保您的包结构遵循 spring 约定,以便 spring 可以发现所有组件,否则配置会很有趣:@ComponentScan、@EntityScan 和 @EnableMongoRepositories。

一张图说一千个字

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

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

于 2017-09-30T00:10:15.667 回答
-1

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

于 2012-03-26T16:04:26.020 回答
-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
    }
}

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

于 2012-10-16T16:18:32.680 回答