37.数据访问

配置一个数据源

  • 想要覆盖默认的设置只需要定义一个你自己的DataSource类型的 @Bean 。Spring Boot提供一个工具构建类DataSourceBuilder,可用来创建一个标准的DataSource(如果它处于classpath下),或者仅创建你自己的DataSource,然后将它和在Section 23.7.1, “Third-party configuration”解释的一系列Environment属性绑定。

比如:

@Bean
@ConfigurationProperties(prefix="datasource.mine")
public DataSource dataSource() {
    return new FancyDataSource();
}


datasource.mine.jdbcUrl=jdbc:h2:mem:mydb
datasource.mine.user=sa
datasource.mine.poolSize=30

2.配置两个数据源

*创建多个数据源和创建第一个工作都是一样的。如果使用针对JDBC或JPA的默认自动配置,你可能想要将其中一个设置为 @Primary (然后它就能被任何 @Autowired 注入获取)。

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.primary")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix="datasource.secondary")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}

3.使用Spring Data仓库

  • Spring Data可以为你的 @Repository 接口创建各种风格的实现。Spring Boot会为你处理所有事情,只要那些 @Repositories 接口跟你的 @EnableAutoConfiguration 类处于相同的包(或子包)。

  • 对于很多应用来说,你需要做的就是将正确的Spring Data依赖添加到classpath下(对于JPA有一个 spring-boot-starterdata-jpa ,对于Mongodb有一个 spring-boot-starter-data-mongodb ),创建一些repository接口来处理 @Entity 对象。具体参考JPA sample或Mongodb sample。

  • Spring Boot会基于它找到的 @EnableAutoConfiguration 来尝试猜测你的 @Repository 定义的位置。想要获取更多控制,可以使用 @EnableJpaRepositories 注解(来自Spring Data JPA)。

4.从Spring配置分离 @Entity 定义

  • Spring Boot会基于它找到的 @EnableAutoConfiguration 来尝试猜测你的 @Entity 定义的位置。想要获取更多控制,你可以使用 @EntityScan 注解,比如:

      @Configuration
      @EnableAutoConfiguration
      @EntityScan(basePackageClasses=City.class)
      public class Application {
      //...
      }
    

5.配置JPA属性

  • Spring Data JPA已经提供了一些独立的配置选项(比如,针对SQL日志),并且Spring Boot会暴露它们,针对hibernate的外部配置属性也更多些。最常见的选项如下:

      spring.jpa.hibernate.ddl-auto: create-drop
      spring.jpa.hibernate.naming_strategy: org.hibernate.cfg.ImprovedNamingStrategy
      spring.jpa.database: H2
      spring.jpa.show-sql: true
    
  • (由于宽松的数据绑定策略,连字符或下划线作为属性keys作用应该是等效的) ddl-auto 配置是个特殊情况,它有不同的默认设置,这取决于你是否使用一个内嵌数据库(create-drop)。当本地EntityManagerFactory被创建时,所有 spring.jpa.properties.* 属性都被作为正常的JPA属性(去掉前缀)传递进去了。

6.使用自定义的EntityManagerFactory

  • 为了完全控制EntityManagerFactory的配置,你需要添加一个名为 entityManagerFactory 的 @Bean 。Spring Boot自动配置会根据是否存在该类型的bean来关闭它的实体管理器(entity manager)。

7.使用两个EntityManagers

  • 即使默认的EntityManagerFactory工作的很好,你也需要定义一个新的EntityManagerFactory,因为一旦出现第二个该类型的bean,默认的将会被关闭。为了轻松的实现该操作,你可以使用Spring Boot提供的EntityManagerBuilder,或者如果你喜欢
    的话可以直接使用来自Spring ORM的LocalContainerEntityManagerFactoryBean。

示例:

// add two data sources configured as above
@Bean
public LocalContainerEntityManagerFactoryBean customerEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    return builder
            .dataSource(customerDataSource())
            .packages(Customer.class)
            .persistenceUnit("customers")
            .build();
}
@Bean
public LocalContainerEntityManagerFactoryBean orderEntityManagerFactory(
        EntityManagerFactoryBuilder builder) {
    return builder
            .dataSource(orderDataSource())
            .packages(Order.class)
            .persistenceUnit("orders")
            .build();
}
  • 上面的配置靠自己基本可以运行。想要完成作品你也需要为两个EntityManagers配置TransactionManagers。其中的一个会被Spring Boot默认的JpaTransactionManager获取,如果你将它标记为 @Primary 。另一个需要显式注入到一个新实例。或你可以使用一个JTA事物管理器生成它两个。

8.使用普通的persistence.xml

  • Spring不要求使用XML配置JPA提供者(provider),并且Spring Boot假定你想要充分利用该特性。如果你倾向于使用 persistence.xml ,那你需要定义你自己的id为'entityManagerFactory'的LocalEntityManagerFactoryBean类型的 @Bean ,并在那设置持久化单元的名称。

9.使用Spring Data JPA和Mongo仓库

  • Spring Data JPA和Spring Data Mongo都能自动为你创建Repository实现。如果它们同时出现在classpath下,你可能需要添加额外的配置来告诉Spring Boot你想要哪个(或两个)为你创建仓库。最明确地方式是使用标准的Spring Data @EnableRepositories ,然后告诉它你的Repository接口的位置(此处即可以是Jpa,也可以是Mongo,或者两者都是)。

  • 这里也有 spring.data.*.repositories.enabled 标志,可用来在外部配置中开启或关闭仓库的自动配置。这在你想关闭Mongo仓库,但仍旧使用自动配置的MongoTemplate时非常有用。

  • 相同的障碍和特性也存在于其他自动配置的Spring Data仓库类型(Elasticsearch, Solr)。只需要改变对应注解的名称和标志。

10.将Spring Data仓库暴露为REST端点

  • Spring Data REST能够将Repository的实现暴露为REST端点,只要该应用启用Spring MVC。

  • Spring Boot暴露一系列来自 spring.data.rest 命名空间的有用属性来定制化RepositoryRestConfiguration。如果需要提供其他定制,你可以创建一个继承自SpringBoot RepositoryRestMvcConfiguration的 @Configuration 类。该类功能和
    RepositoryRestMvcConfiguration相同,但允许你继续使用 spring.data.rest.* 属性。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容