0%

自定义Repository实现

文章字数:331,阅读全文大约需要1分钟

在jpa的基础上增加自己的实现 原文

核心代码

  1. 创建一个中间层Dao,继承jpa的两个接口,并用注解注释

    1
    2
    @NoRepositoryBean
    public interface BaseDao<T,ID extends Serializable> extends JpaRepository<T,ID>,JpaSpecificationExecutor<T>
  2. 创建上面的dao+impl的实现类,拓展功能。

  3. 其它dao直接继承与BeseDao

@NoRepositoryBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package org.springframework.data.repository;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Annotation to exclude repository interfaces from being picked up and thus in consequence getting an instance being
* created.
* <p/>
* This will typically be used when providing an extended base interface for all repositories in combination with a
* custom repository base class to implement methods declared in that intermediate interface. In this case you typically
* derive your concrete repository interfaces from the intermediate one but don't want to create a Spring bean for the
* intermediate interface.
*
* @author Oliver Gierke
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface NoRepositoryBean {

}

翻译

1
2
当为所有存储库提供扩展的基础接口,并结合自定义存储库基类以实现在该中间接口中声明的方法时,通常会使用此方法。 
在这种情况下,您通常会从中间接口派生出具体的存储库接口,但又不想为中间接口创建Spring bean。

配置开启功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package com.data.jpa.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.web.config.EnableSpringDataWebSupport;
/**
* 通过注解配置factory-class
* @author xiaowen
* @date 2016年5月30日
* @ version 1.0
*/
@Configuration
@EnableJpaRepositories(basePackages = "com.data.jpa**.dao",
repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class)
@EnableSpringDataWebSupport
public class JpaDataConfig {

}

这个注解是为基类仓库拓展准备的