@EnableJpaRepositories配置详解

1,简单配置

@EnableJpaRepositories(“com.juzi.repository”)
或者 @EnableJpaRepositories({“com.juzi.repository”, “com.cshtong.second.repository”})

2,完整的@EnableJpaRepositories注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@EnableJpaRepositories(
basePackages = {},
basePackageClasses = {},
includeFilters = {},
excludeFilters = {},
repositoryImplementationPostfix = "Impl",
namedQueriesLocation = "",//META-INF/jpa-named-queries.properties
queryLookupStrategy=QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND, //QueryLookupStrategy.Key.x
repositoryFactoryBeanClass=JpaRepositoryFactoryBean.class, //class
entityManagerFactoryRef="entityManagerFactory",
transactionManagerRef="transactionManager",
considerNestedRepositories=false,
enableDefaultTransactions=true
)

各个配置项的作用
1)basePackage
用于配置扫描Repositories所在的package及子package。简单配置中的配置则等同于此项配置值,
basePackages可以配置为单个字符串,也可以配置为字符串数组形式。

1
2
3
4
5
@EnableJpaRepositories(
basePackages = "com.juzi")
多个包路径
@EnableJpaRepositories(
basePackages = {"com.juzi.repository", "com.juzi.second.repository"})

2)basePackageClasses
指定 Repository 类

1
2
3
4
@EnableJpaRepositories(basePackageClasses = BookRepository.class)
@EnableJpaRepositories(
basePackageClasses = {ShopRepository.class, OrganizationRepository.class})

3)includeFilters
过滤器,该过滤区采用ComponentScan的过滤器类
@EnableJpaRepositories(
includeFilters={@ComponentScan.Filter(type=FilterType.ANNOTATION, value=Repository.class)})
4)excludeFilters
不包含过滤器

@EnableJpaRepositories(
excludeFilters={
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=Service.class),
@ComponentScan.Filter(type=FilterType.ANNOTATION, value=Controller.class)})

5)repositoryImplementationPostfix
实现类追加的尾部,比如ShopRepository,对应的为ShopRepositoryImpl

6)namedQueriesLocation
named SQL存放的位置,默认为META-INF/jpa-named-queries.properties

7)queryLookupStrategy
构建条件查询的策略,包含三种方式CREATE,USE_DECLARED_QUERY,CREATE_IF_NOT_FOUND

CREATE:按照接口名称自动构建查询
USE_DECLARED_QUERY:用户声明查询
CREATE_IF_NOT_FOUND:先搜索用户声明的,不存在则自动构建

8)repositoryFactoryBeanClass
指定Repository的工厂类

9)entityManagerFactoryRef
实体管理工厂引用名称,对应到@Bean注解对应的方法

10)transactionManagerRef

事务管理工厂引用名称,对应到@Bean注解对应的方法