37.數(shù)據(jù)訪問

配置一個(gè)數(shù)據(jù)源

  • 想要覆蓋默認(rèn)的設(shè)置只需要定義一個(gè)你自己的DataSource類型的 @Bean 。Spring Boot提供一個(gè)工具構(gòu)建類DataSourceBuilder,可用來創(chuàng)建一個(gè)標(biāo)準(zhǔn)的DataSource(如果它處于classpath下),或者僅創(chuàng)建你自己的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.配置兩個(gè)數(shù)據(jù)源

*創(chuàng)建多個(gè)數(shù)據(jù)源和創(chuàng)建第一個(gè)工作都是一樣的。如果使用針對(duì)JDBC或JPA的默認(rèn)自動(dòng)配置,你可能想要將其中一個(gè)設(shè)置為 @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 接口創(chuàng)建各種風(fēng)格的實(shí)現(xiàn)。Spring Boot會(huì)為你處理所有事情,只要那些 @Repositories 接口跟你的 @EnableAutoConfiguration 類處于相同的包(或子包)。

  • 對(duì)于很多應(yīng)用來說,你需要做的就是將正確的Spring Data依賴添加到classpath下(對(duì)于JPA有一個(gè) spring-boot-starterdata-jpa ,對(duì)于Mongodb有一個(gè) spring-boot-starter-data-mongodb ),創(chuàng)建一些repository接口來處理 @Entity 對(duì)象。具體參考JPA sample或Mongodb sample。

  • Spring Boot會(huì)基于它找到的 @EnableAutoConfiguration 來嘗試猜測你的 @Repository 定義的位置。想要獲取更多控制,可以使用 @EnableJpaRepositories 注解(來自Spring Data JPA)。

4.從Spring配置分離 @Entity 定義

  • Spring Boot會(huì)基于它找到的 @EnableAutoConfiguration 來嘗試猜測你的 @Entity 定義的位置。想要獲取更多控制,你可以使用 @EntityScan 注解,比如:

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

5.配置JPA屬性

  • Spring Data JPA已經(jīng)提供了一些獨(dú)立的配置選項(xiàng)(比如,針對(duì)SQL日志),并且Spring Boot會(huì)暴露它們,針對(duì)hibernate的外部配置屬性也更多些。最常見的選項(xiàng)如下:

      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
    
  • (由于寬松的數(shù)據(jù)綁定策略,連字符或下劃線作為屬性keys作用應(yīng)該是等效的) ddl-auto 配置是個(gè)特殊情況,它有不同的默認(rèn)設(shè)置,這取決于你是否使用一個(gè)內(nèi)嵌數(shù)據(jù)庫(create-drop)。當(dāng)本地EntityManagerFactory被創(chuàng)建時(shí),所有 spring.jpa.properties.* 屬性都被作為正常的JPA屬性(去掉前綴)傳遞進(jìn)去了。

6.使用自定義的EntityManagerFactory

  • 為了完全控制EntityManagerFactory的配置,你需要添加一個(gè)名為 entityManagerFactory 的 @Bean 。Spring Boot自動(dòng)配置會(huì)根據(jù)是否存在該類型的bean來關(guān)閉它的實(shí)體管理器(entity manager)。

7.使用兩個(gè)EntityManagers

  • 即使默認(rèn)的EntityManagerFactory工作的很好,你也需要定義一個(gè)新的EntityManagerFactory,因?yàn)橐坏┏霈F(xiàn)第二個(gè)該類型的bean,默認(rèn)的將會(huì)被關(guān)閉。為了輕松的實(shí)現(xiàn)該操作,你可以使用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();
}
  • 上面的配置靠自己基本可以運(yùn)行。想要完成作品你也需要為兩個(gè)EntityManagers配置TransactionManagers。其中的一個(gè)會(huì)被Spring Boot默認(rèn)的JpaTransactionManager獲取,如果你將它標(biāo)記為 @Primary 。另一個(gè)需要顯式注入到一個(gè)新實(shí)例?;蚰憧梢允褂靡粋€(gè)JTA事物管理器生成它兩個(gè)。

8.使用普通的persistence.xml

  • Spring不要求使用XML配置JPA提供者(provider),并且Spring Boot假定你想要充分利用該特性。如果你傾向于使用 persistence.xml ,那你需要定義你自己的id為'entityManagerFactory'的LocalEntityManagerFactoryBean類型的 @Bean ,并在那設(shè)置持久化單元的名稱。

9.使用Spring Data JPA和Mongo倉庫

  • Spring Data JPA和Spring Data Mongo都能自動(dòng)為你創(chuàng)建Repository實(shí)現(xiàn)。如果它們同時(shí)出現(xiàn)在classpath下,你可能需要添加額外的配置來告訴Spring Boot你想要哪個(gè)(或兩個(gè))為你創(chuàng)建倉庫。最明確地方式是使用標(biāo)準(zhǔn)的Spring Data @EnableRepositories ,然后告訴它你的Repository接口的位置(此處即可以是Jpa,也可以是Mongo,或者兩者都是)。

  • 這里也有 spring.data.*.repositories.enabled 標(biāo)志,可用來在外部配置中開啟或關(guān)閉倉庫的自動(dòng)配置。這在你想關(guān)閉Mongo倉庫,但仍舊使用自動(dòng)配置的MongoTemplate時(shí)非常有用。

  • 相同的障礙和特性也存在于其他自動(dòng)配置的Spring Data倉庫類型(Elasticsearch, Solr)。只需要改變對(duì)應(yīng)注解的名稱和標(biāo)志。

10.將Spring Data倉庫暴露為REST端點(diǎn)

  • Spring Data REST能夠?qū)epository的實(shí)現(xiàn)暴露為REST端點(diǎn),只要該應(yīng)用啟用Spring MVC。

  • Spring Boot暴露一系列來自 spring.data.rest 命名空間的有用屬性來定制化RepositoryRestConfiguration。如果需要提供其他定制,你可以創(chuàng)建一個(gè)繼承自SpringBoot RepositoryRestMvcConfiguration的 @Configuration 類。該類功能和
    RepositoryRestMvcConfiguration相同,但允許你繼續(xù)使用 spring.data.rest.* 屬性。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容