欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解spring boot實(shí)現(xiàn)多數(shù)據(jù)源代碼實(shí)戰(zhàn)

 更新時(shí)間:2017年07月25日 10:16:32   作者:小恩  
本篇文章主要介紹了詳解spring boot實(shí)現(xiàn)多數(shù)據(jù)源代碼實(shí)戰(zhàn),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

之前在介紹使用JdbcTemplate和Spring-data-jpa時(shí),都使用了單數(shù)據(jù)源。在單數(shù)據(jù)源的情況下,Spring Boot的配置非常簡(jiǎn)單,只需要在application.properties文件中配置連接參數(shù)即可。但是往往隨著業(yè)務(wù)量發(fā)展,我們通常會(huì)進(jìn)行數(shù)據(jù)庫(kù)拆分或是引入其他數(shù)據(jù)庫(kù),從而我們需要配置多個(gè)數(shù)據(jù)源,下面基于之前的JdbcTemplate和Spring-data-jpa例子分別介紹兩種多數(shù)據(jù)源的配置方式。

多數(shù)據(jù)源配置

創(chuàng)建一個(gè)Spring配置類,定義兩個(gè)DataSource用來(lái)讀取application.properties中的不同配置。如下例子中,主數(shù)據(jù)源配置為spring.datasource.primary開頭的配置,第二數(shù)據(jù)源配置為spring.datasource.secondary開頭的配置。

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

對(duì)應(yīng)的application.properties配置如下:

spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=root
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=root
spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver

JdbcTemplate支持

對(duì)JdbcTemplate的支持比較簡(jiǎn)單,只需要為其注入對(duì)應(yīng)的datasource即可,如下例子,在創(chuàng)建JdbcTemplate的時(shí)候分別注入名為primaryDataSource和secondaryDataSource的數(shù)據(jù)源來(lái)區(qū)分不同的JdbcTemplate。

@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
    @Qualifier("primaryDataSource") DataSource dataSource) {
  return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
    @Qualifier("secondaryDataSource") DataSource dataSource) {
  return new JdbcTemplate(dataSource);
}

接下來(lái)通過(guò)測(cè)試用例來(lái)演示如何使用這兩個(gè)針對(duì)不同數(shù)據(jù)源的JdbcTemplate。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
  @Autowired
  @Qualifier("primaryJdbcTemplate")
  protected JdbcTemplate jdbcTemplate1;
  @Autowired
  @Qualifier("secondaryJdbcTemplate")
  protected JdbcTemplate jdbcTemplate2;
  @Before
  public void setUp() {
    jdbcTemplate1.update("DELETE FROM USER ");
    jdbcTemplate2.update("DELETE FROM USER ");
  }
  @Test
  public void test() throws Exception {
    // 往第一個(gè)數(shù)據(jù)源中插入兩條數(shù)據(jù)
    jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
    jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 2, "bbb", 30);
    // 往第二個(gè)數(shù)據(jù)源中插入一條數(shù)據(jù),若插入的是第一個(gè)數(shù)據(jù)源,則會(huì)主鍵沖突報(bào)錯(cuò)
    jdbcTemplate2.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
    // 查一下第一個(gè)數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗(yàn)證插入是否成功
    Assert.assertEquals("2", jdbcTemplate1.queryForObject("select count(1) from user", String.class));
    // 查一下第一個(gè)數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗(yàn)證插入是否成功
    Assert.assertEquals("1", jdbcTemplate2.queryForObject("select count(1) from user", String.class));
  }
}

完整示例:Chapter3-2-3

Spring-data-jpa支持

對(duì)于數(shù)據(jù)源的配置可以沿用上例中DataSourceConfig的實(shí)現(xiàn)。

新增對(duì)第一數(shù)據(jù)源的JPA配置,注意兩處注釋的地方,用于指定數(shù)據(jù)源對(duì)應(yīng)的Entity實(shí)體和Repository定義位置,用@Primary區(qū)分主數(shù)據(jù)源。

新增對(duì)第二數(shù)據(jù)源的JPA配置,內(nèi)容與第一數(shù)據(jù)源類似,具體如下:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef="entityManagerFactorySecondary",
    transactionManagerRef="transactionManagerSecondary",
    basePackages= { "com.didispace.domain.s" }) //設(shè)置Repository所在位置
public class SecondaryConfig {
  @Autowired @Qualifier("secondaryDataSource")
  private DataSource secondaryDataSource;
  @Bean(name = "entityManagerSecondary")
  public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
    return entityManagerFactorySecondary(builder).getObject().createEntityManager();
  }
  @Bean(name = "entityManagerFactorySecondary")
  public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(secondaryDataSource)
        .properties(getVendorProperties(secondaryDataSource))
        .packages("com.didispace.domain.s") //設(shè)置實(shí)體類所在位置
        .persistenceUnit("secondaryPersistenceUnit")
        .build();
  }
  @Autowired
  private JpaProperties jpaProperties;
  private Map<String, String> getVendorProperties(DataSource dataSource) {
    return jpaProperties.getHibernateProperties(dataSource);
  }
  @Bean(name = "transactionManagerSecondary")
  PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
    return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
  }
}

完成了以上配置之后,主數(shù)據(jù)源的實(shí)體和數(shù)據(jù)訪問(wèn)對(duì)象位于:com.didispace.domain.p,次數(shù)據(jù)源的實(shí)體和數(shù)據(jù)訪問(wèn)接口位于:com.didispace.domain.s。

分別在這兩個(gè)package下創(chuàng)建各自的實(shí)體和數(shù)據(jù)訪問(wèn)接口

主數(shù)據(jù)源下,創(chuàng)建User實(shí)體和對(duì)應(yīng)的Repository接口

@Entity
public class User {
  @Id
  @GeneratedValue
  private Long id;
  @Column(nullable = false)
  private String name;
  @Column(nullable = false)
  private Integer age;
  public User(){}
  public User(String name, Integer age) {
    this.name = name;
    this.age = age;
  }
  // 省略getter、setter
}

public interface UserRepository extends JpaRepository<User, Long> {
}

從數(shù)據(jù)源下,創(chuàng)建Message實(shí)體和對(duì)應(yīng)的Repository接口

@Entity
public class Message {
  @Id
  @GeneratedValue
  private Long id;
  @Column(nullable = false)
  private String name;
  @Column(nullable = false)
  private String content;
  public Message(){}
  public Message(String name, String content) {
    this.name = name;
    this.content = content;
  }
  // 省略getter、setter
}
public interface MessageRepository extends JpaRepository<Message, Long> {
}

接下來(lái)通過(guò)測(cè)試用例來(lái)驗(yàn)證使用這兩個(gè)針對(duì)不同數(shù)據(jù)源的配置進(jìn)行數(shù)據(jù)操作。

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
  @Autowired
  private UserRepository userRepository;
  @Autowired
  private MessageRepository messageRepository;
  @Test
  public void test() throws Exception {
    userRepository.save(new User("aaa", 10));
    userRepository.save(new User("bbb", 20));
    userRepository.save(new User("ccc", 30));
    userRepository.save(new User("ddd", 40));
    userRepository.save(new User("eee", 50));
    Assert.assertEquals(5, userRepository.findAll().size());
    messageRepository.save(new Message("o1", "aaaaaaaaaa"));
    messageRepository.save(new Message("o2", "bbbbbbbbbb"));
    messageRepository.save(new Message("o3", "cccccccccc"));
    Assert.assertEquals(3, messageRepository.findAll().size());
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 淺談Spring框架中@Autowired和@Resource的區(qū)別

    淺談Spring框架中@Autowired和@Resource的區(qū)別

    最近review別人代碼的時(shí)候,看到了一些@Autowired不一樣的用法,覺得有些意思,下面這篇文章主要給大家介紹了關(guān)于Spring框架中@Autowired和@Resource區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2022-10-10
  • Java switch支持的數(shù)據(jù)類型詳解

    Java switch支持的數(shù)據(jù)類型詳解

    這篇文章主要介紹了Java switch支持的數(shù)據(jù)類型詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • 一文秒懂通過(guò)JavaCSV類庫(kù)讀寫CSV文件的技巧

    一文秒懂通過(guò)JavaCSV類庫(kù)讀寫CSV文件的技巧

    本文給大家推薦第三方工具庫(kù) JavaCSV,用來(lái)造一些 csv 測(cè)試數(shù)據(jù)文件,使用超級(jí)方便,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2021-05-05
  • Java源碼解析ThreadLocal及使用場(chǎng)景

    Java源碼解析ThreadLocal及使用場(chǎng)景

    今天小編就為大家分享一篇關(guān)于Java源碼解析ThreadLocal及使用場(chǎng)景,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • Spring的注解簡(jiǎn)單介紹

    Spring的注解簡(jiǎn)單介紹

    這篇文章主要介紹了Spring的注解簡(jiǎn)單介紹,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2017-12-12
  • 解決Spring使用@MapperScan問(wèn)題

    解決Spring使用@MapperScan問(wèn)題

    這篇文章主要介紹了解決Spring使用@MapperScan問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Spring?web開發(fā)教程之Request獲取3種方式

    Spring?web開發(fā)教程之Request獲取3種方式

    這篇文章主要給大家介紹了關(guān)于Spring?web開發(fā)教程之Request獲取3種方式的相關(guān)資料,request對(duì)象是從客戶端向服務(wù)器發(fā)出請(qǐng)求,包括用戶提交的信息以及客戶端的一些信息,需要的朋友可以參考下
    2023-11-11
  • nexus私服啟動(dòng)不了問(wèn)題及解決

    nexus私服啟動(dòng)不了問(wèn)題及解決

    這篇文章主要介紹了nexus私服啟動(dòng)不了問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java CRM系統(tǒng)用戶登錄功能實(shí)現(xiàn)代碼實(shí)例

    Java CRM系統(tǒng)用戶登錄功能實(shí)現(xiàn)代碼實(shí)例

    這篇文章主要介紹了Java CRM系統(tǒng)用戶登錄功能實(shí)現(xiàn)代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot中yml的數(shù)據(jù)綁定示例

    SpringBoot中yml的數(shù)據(jù)綁定示例

    本文主要介紹了SpringBoot中yml的數(shù)據(jù)綁定示例,借助于YAML的簡(jiǎn)潔語(yǔ)法和結(jié)構(gòu)化特性,我們能夠輕松地管理應(yīng)用程序的配置信息,使得配置文件更加清晰易讀,感興趣的可以了解一下
    2023-11-11

最新評(píng)論