在Spring JPA中扩展接口以创建存储库的想法是什么?

时间:2015-12-21 15:29:47

标签: java spring spring-data spring-data-jpa

is said here,要将一个方法添加到存储库,需要创建3个(三个)类或接口。

这是真的,这种曼波 - 杨波的目的是什么?接口扩展的唯一好处是能够通过命名约定来创建方法吗?这种好处是否真的超过了创建自己方法的能力的损失?

更新

为什么我不能implements CrudRepository

我尝试使用implements

// does not work
//public abstract class CustomerRepository implements CrudRepository<Customer, Long> {
//
//    abstract List<Customer> findByLastName(String lastName);
//}

// works
public interface CustomerRepository extends CrudRepository<Customer, Long> {

    List<Customer> findByLastName(String lastName);
}

但它不适用于错误

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demo' defined in hello.Application: Unsatisfied dependency expressed through constructor argument with index 0 of type 
[hello.CustomerRepository]: : No qualifying bean of type [hello.CustomerRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [hello.CustomerRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

1 个答案:

答案 0 :(得分:2)

如果你只想进行crud和pagination操作,Spring已经提供了这些操作的实现,尽管它们是接口。你不必实现任何这些。你只需要扩展crud,如果需要分页界面。 Spring将扫描存储库接口并为crud,分页操作,带有查询注释的带注释的接口方法以及方法提供实现,如果你遵守Spring数据给出的规则,如findByLastname()。

有时候需要提供自己的实施。在这种情况下,您需要按照文档进行操作以提供自己的实现。

Spring数据搜索扩展Repository接口的接口。而不是抽象类。

链接:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.create-instances

该链接中的文字

  

在前面的示例中,指示Spring扫描com.acme.repositories及其所有子包,以查找扩展Repository或其子接口的接口。对于找到的每个接口,基础结构都会注册特定于持久性技术的FactoryBean,以创建处理查询方法调用的相应代理。每个bean都是在从接口名称派生的bean名称下注册的,因此UserRepository的接口将在userRepository下注册。 base-package属性允许使用通配符,以便您可以定义扫描包的模式。

Repository接口的Javadoc:

  

org.springframework.data.repository.Repository
  中央存储库标记界面。捕获要管理的域类型以及域类型的ID类型。一般用途是保存类型信息,并且能够在类路径扫描期间发现扩展此类型的接口,以便轻松创建Spring bean。

  扩展此接口的域存储库可以通过简单地声明与CrudRepository中声明的签名相同的签名方法来有选择地公开CRUD方法。