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

解決spring boot 1.5.4 配置多數(shù)據(jù)源的問(wèn)題

 更新時(shí)間:2017年06月18日 09:08:21   投稿:jingxian  
下面小編就為大家?guī)?lái)一篇解決spring boot 1.5.4 配置多數(shù)據(jù)源的問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

spring boot 已經(jīng)支持多數(shù)據(jù)源配置了,無(wú)需網(wǎng)上好多那些編寫什么類的,特別麻煩,看看如下解決方案,官方的,放心!

1.首先定義數(shù)據(jù)源配置

#=====================multiple database config============================
#ds1
first.datasource.url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true
first.datasource.username=root
first.datasource.password=123456
first.datasource.driver-class-name=com.mysql.jdbc.Driver
first.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
first.datasource.max-wait=10000
first.datasource.max-active=200
first.datasource.test-on-borrow=true
first.datasource.initial-size=10

#ds2
second.datasource.url=jdbc:mysql://localhost/test2?characterEncoding=utf8&useSSL=true
second.datasource.username=root
second.datasource.password=123456
second.datasource.driver-class-name=com.mysql.jdbc.Driver
second.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
second.datasource.max-wait=10000
second.datasource.max-active=200
second.datasource.test-on-borrow=true
second.datasource.initial-size=10

#=====================jpa config================================
#實(shí)體類維護(hù)數(shù)據(jù)庫(kù)表結(jié)構(gòu)的具體行為:update/create/create-drop/validate/none
spring.jpa.hibernate.ddl-auto=none
#打印sql語(yǔ)句
spring.jpa.show-sql=true
#格式化輸出的json字符串
spring.jackson.serialization.indent_output=true

2.配置ds1的相關(guān)注入對(duì)象和啟用jpa支持

/**
 * Created by hdwang on 2017-06-16.
 * 第一個(gè)數(shù)據(jù)源配置
 * If you are using Spring Data, you need to configure @EnableJpaRepositories
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.hdwang.dao.datajpa.firstDs",entityManagerFactoryRef = "firstEntityManagerFactory",transactionManagerRef="firstTransactionManager")
public class FirstDsConfig {

  /**
   * 數(shù)據(jù)源配置對(duì)象
   * Primary 表示默認(rèn)的對(duì)象,Autowire可注入,不是默認(rèn)的得明確名稱注入
   * @return
   */
  @Bean
  @Primary
  @ConfigurationProperties("first.datasource")
  public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
  }

  /**
   * 數(shù)據(jù)源對(duì)象
   * @return
   */
  @Bean
  @Primary
  @ConfigurationProperties("first.datasource")
  public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
  }

  /**
   * 實(shí)體管理對(duì)象
   * @param builder 由spring注入這個(gè)對(duì)象,首先根據(jù)type注入(多個(gè)就取聲明@Primary的對(duì)象),否則根據(jù)name注入
   * @return
   */
  @Bean
  @Primary
  public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory(
      EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(firstDataSource())
        .packages("com.hdwang.entity.dbFirst")
        .persistenceUnit("firstDs")
        .build();
  }

  /**
   * 事務(wù)管理對(duì)象
   * @return
   */
  @Bean(name = "firstTransactionManager")
  @Primary
  public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);
    return transactionManager;
  }

  @Bean
  @Primary
  public JdbcTemplate jdbcTemplate(){
    return new JdbcTemplate(firstDataSource());
  }

  @Bean
  @Primary
  public TransactionTemplate transactionTemplate(PlatformTransactionManager platformTransactionManager){
    return new TransactionTemplate(platformTransactionManager);
  }
}

相關(guān)知識(shí)點(diǎn):

1.使用@Bean可以創(chuàng)建一個(gè)bean對(duì)象交給spring容器管理

2.@Bean創(chuàng)建的bean對(duì)象的名稱默認(rèn)為方法名,也可以指定

3.@Bean方法參數(shù)表示,接收一個(gè)bean對(duì)象,默認(rèn)按照type類型接收注入的對(duì)象,若要修改為byName方式,可以使用@Qualifier注解注入準(zhǔn)確的對(duì)象

4.@Primary表示該bean為此類型的默認(rèn)bean,在其他地方引用的時(shí)候用@Autowired即可按照類型注入,不受同類型多個(gè)對(duì)象影響

5.EnableJpaRepositories表示啟用spring data jpa的支持,也就是jpa的新使用方式,注意basePackages指的事 @Repository接口的所在包位置,可配置多個(gè)

其他注解就不清楚了!

2.配置ds2的相關(guān)注入對(duì)象和啟用jpa支持

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.hdwang.dao.datajpa.secondDs", entityManagerFactoryRef = "secondEntityManagerFactory",transactionManagerRef = "secondTransactionManager")
public class SecondDsConfig {

  @Bean
  @ConfigurationProperties("second.datasource")
  public DataSourceProperties secondDataSourceProperties() {
    return new DataSourceProperties();
  }

  @Bean
  @ConfigurationProperties("second.datasource")
  public DataSource secondDataSource() {
    return secondDataSourceProperties().initializeDataSourceBuilder().build();
  }

  /**
   * 實(shí)體管理對(duì)象
   * @param builder 由spring注入這個(gè)對(duì)象,首先根據(jù)type注入(多個(gè)就取聲明@Primary的對(duì)象),否則根據(jù)name注入
   * @return
   */
  @Bean
  public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory(
      EntityManagerFactoryBuilder builder) {
    return builder
        .dataSource(secondDataSource())
        .packages("com.hdwang.entity.dbSecond")
        .persistenceUnit("secondDs")
        .build();
  }

  /**
   * 事物管理對(duì)象
   * @param secondEntityManagerFactory 實(shí)體管理工廠對(duì)象(按照名稱注入)
   * @return 平臺(tái)事物管理器
   */
  @Bean(name = "secondTransactionManager")
  public PlatformTransactionManager transactionManager(@Qualifier("secondEntityManagerFactory")LocalContainerEntityManagerFactoryBean secondEntityManagerFactory){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(secondEntityManagerFactory.getObject());
    return transactionManager;
  }

  @Bean(name="jdbcTemplate2")
  public JdbcTemplate jdbcTemplate(){
    return new JdbcTemplate(secondDataSource());
  }

  @Bean(name = "transactionTemplate2")
  public TransactionTemplate transactionTemplate(@Qualifier("secondTransactionManager")PlatformTransactionManager transactionManager){
    return new TransactionTemplate(transactionManager);
  }
}

3.Repository數(shù)據(jù)持久層

package com.hdwang.dao.datajpa.firstDs;

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
  /**
   * spring data jpa 會(huì)自動(dòng)注入實(shí)現(xiàn)(根據(jù)方法命名規(guī)范)
   * @return
   */
  User findByNumber(String number);


  @Modifying
  @Query("delete from User u where u.id = :id")
  void deleteUser(@Param("id")int id);
}
package com.hdwang.dao.datajpa.secondDs;

@Repository
public interface OrderRepository extends JpaRepository<Order, Integer> {
  /**
   * spring data jpa 會(huì)自動(dòng)注入實(shí)現(xiàn)(根據(jù)方法命名規(guī)范)
   * @return
   */
  User findByNumber(String number);


  @Modifying
  @Query("delete from Order o where o.id = :id")
  void deleteUser(@Param("id") int id);
}

上面兩個(gè)接口分屬兩個(gè)數(shù)據(jù)源,在@EnableJpaRepositories配置好后,這里就可以正確操作相應(yīng)的數(shù)據(jù)源了

4.Service服務(wù)層,注意事物(接口我就不貼了)

@Service
@Transactional("firstTransactionManager")
public class UserServiceImpl implements UserService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public User findById(int id) {
    return this.userRepository.findOne(id);
  }

  @Override
  public User findByNumber(String number) {
    return this.userRepository.findByNumber(number);
  }

  @Override
  public List<User> findAllUserByPage(int page,int size) {
    Pageable pageable = new PageRequest(page, size);
    Page<User> users = this.userRepository.findAll(pageable);
    return users.getContent();
  }

  @Override
  public User updateUser(User user,boolean throwEx) {
    User userNew = this.userRepository.save(user);
    if(throwEx){
      throw new RuntimeException("throw a ex");
    }
    return userNew;
  }

  @Override
  public void deleteUser(int id) {
    this.userRepository.deleteUser(id);
  }
}
@Service
@Transactional("secondTransactionManager")
public class OrderServiceImpl implements OrderService {

  @Autowired
  private OrderRepository orderRepository;


  @Override
  public Order findById(int id) {
    return this.orderRepository.findOne(id);
  }

  @Override
  public Order updateOrder(Order order, boolean throwEx) {
    Order orderNew = this.orderRepository.save(order);
    if(throwEx){
      throw new RuntimeException("throw a ex");
    }
    return orderNew;
  }
}

知識(shí)擴(kuò)展

1.如果采用傳統(tǒng)jpa方式,@EnableJpaRepositories無(wú)需配置,配置了也無(wú)影響。實(shí)現(xiàn)方式如下:

ds1相關(guān)DaoImpl
@PersistenceContext
private EntityManager entityManager;

ds2相關(guān)DaoImpl
@PersistenceContext(unitName = "secondDs")
private EntityManager entityManager;

因?yàn)閐s1的entityManger聲明了@Primary,所以無(wú)需指明unitName,ds2必須指明。注入了準(zhǔn)確的entityManager,就可以直接拿來(lái)操作數(shù)據(jù)庫(kù)了。service層和上面一樣的,@Transactional("xxxManager")指明事物管理器即可!

2.采用jdbcTemplate方式,直接注入到Service層對(duì)象即可,so easy!

@Autowired
private JdbcTemplate jdbcTemplate;

@Autowired
private TransactionTemplate transactionTemplate;

@Resource(name="jdbcTemplate2")
private JdbcTemplate jdbcTemplate2;

@Resource(name="transactionTemplate2")
private TransactionTemplate transactionTemplate2;

好了,spring boot 多數(shù)據(jù)源,完美解決! 而且三種數(shù)據(jù)庫(kù)操作方法均支持,包括事物。已經(jīng)經(jīng)過(guò)實(shí)踐證明了! 這是官方給出的最佳實(shí)踐,只是官方文檔沒(méi)寫細(xì)。導(dǎo)致整整坑了我?guī)滋?。至此,spring boot框架的使用就告一段落了!

以上這篇解決spring boot 1.5.4 配置多數(shù)據(jù)源的問(wèn)題就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringBoot項(xiàng)目中同時(shí)操作多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法

    SpringBoot項(xiàng)目中同時(shí)操作多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法

    在實(shí)際項(xiàng)目開發(fā)中可能存在需要同時(shí)操作兩個(gè)數(shù)據(jù)庫(kù)的場(chǎng)景,本文主要介紹了SpringBoot項(xiàng)目中同時(shí)操作多個(gè)數(shù)據(jù)庫(kù)的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Java中的@Repeatable注解的作用詳解

    Java中的@Repeatable注解的作用詳解

    這篇文章主要介紹了Java中的@Repeatable注解的作用詳解,@Repeatable注解是用來(lái)標(biāo)注一個(gè)注解在同一個(gè)地方可重復(fù)使用的一個(gè)注解,使被他注釋的注解可以在同一個(gè)地方重復(fù)使用,需要的朋友可以參考下
    2024-01-01
  • Java?Integer如何獲取第一位和最后一位,并截取

    Java?Integer如何獲取第一位和最后一位,并截取

    這篇文章主要介紹了Java?Integer如何獲取第一位和最后一位并截取,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • springMVC如何將controller中Model數(shù)據(jù)傳遞到j(luò)sp頁(yè)面

    springMVC如何將controller中Model數(shù)據(jù)傳遞到j(luò)sp頁(yè)面

    本篇文章主要介紹了springMVC如何將controller中Model數(shù)據(jù)傳遞到j(luò)sp頁(yè)面,具有一定的參考價(jià)值,有興趣的可以了解一下
    2017-07-07
  • Java連接Redis全過(guò)程講解

    Java連接Redis全過(guò)程講解

    這篇文章主要介紹了Java連接Redis全過(guò)程講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • java基礎(chǔ)知識(shí)之FileInputStream流的使用

    java基礎(chǔ)知識(shí)之FileInputStream流的使用

    這篇文章主要介紹了java基礎(chǔ)知識(shí)之FileInputStream流的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • SpringBoot整合BootStrap實(shí)戰(zhàn)

    SpringBoot整合BootStrap實(shí)戰(zhàn)

    這篇文章主要介紹了SpringBoot整合BootStrap實(shí)戰(zhàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Maven的幾個(gè)常用plugin

    Maven的幾個(gè)常用plugin

    本文主要介紹了Maven的幾個(gè)常用plugin。具有一定的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-01-01
  • Java后臺(tái)防止客戶端重復(fù)請(qǐng)求、提交表單實(shí)現(xiàn)原理

    Java后臺(tái)防止客戶端重復(fù)請(qǐng)求、提交表單實(shí)現(xiàn)原理

    這篇文章主要介紹了Java后臺(tái)防止客戶端重復(fù)請(qǐng)求、提交表單實(shí)現(xiàn)原理,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • 使用@CachePut?更新數(shù)據(jù)庫(kù)和更新緩存

    使用@CachePut?更新數(shù)據(jù)庫(kù)和更新緩存

    這篇文章主要介紹了使用@CachePut?更新數(shù)據(jù)庫(kù)和更新緩存方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-12-12

最新評(píng)論