解決spring boot 1.5.4 配置多數(shù)據(jù)源的問題
spring boot 已經(jīng)支持多數(shù)據(jù)源配置了,無需網(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ù)庫表結(jié)構(gòu)的具體行為:update/create/create-drop/validate/none spring.jpa.hibernate.ddl-auto=none #打印sql語句 spring.jpa.show-sql=true #格式化輸出的json字符串 spring.jackson.serialization.indent_output=true
2.配置ds1的相關(guān)注入對象和啟用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ù)源配置對象 * Primary 表示默認(rèn)的對象,Autowire可注入,不是默認(rèn)的得明確名稱注入 * @return */ @Bean @Primary @ConfigurationProperties("first.datasource") public DataSourceProperties firstDataSourceProperties() { return new DataSourceProperties(); } /** * 數(shù)據(jù)源對象 * @return */ @Bean @Primary @ConfigurationProperties("first.datasource") public DataSource firstDataSource() { return firstDataSourceProperties().initializeDataSourceBuilder().build(); } /** * 實(shí)體管理對象 * @param builder 由spring注入這個(gè)對象,首先根據(jù)type注入(多個(gè)就取聲明@Primary的對象),否則根據(jù)name注入 * @return */ @Bean @Primary public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(firstDataSource()) .packages("com.hdwang.entity.dbFirst") .persistenceUnit("firstDs") .build(); } /** * 事務(wù)管理對象 * @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)知識點(diǎn):
1.使用@Bean可以創(chuàng)建一個(gè)bean對象交給spring容器管理
2.@Bean創(chuàng)建的bean對象的名稱默認(rèn)為方法名,也可以指定
3.@Bean方法參數(shù)表示,接收一個(gè)bean對象,默認(rèn)按照type類型接收注入的對象,若要修改為byName方式,可以使用@Qualifier注解注入準(zhǔn)確的對象
4.@Primary表示該bean為此類型的默認(rèn)bean,在其他地方引用的時(shí)候用@Autowired即可按照類型注入,不受同類型多個(gè)對象影響
5.EnableJpaRepositories表示啟用spring data jpa的支持,也就是jpa的新使用方式,注意basePackages指的事 @Repository接口的所在包位置,可配置多個(gè)
其他注解就不清楚了!
2.配置ds2的相關(guān)注入對象和啟用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í)體管理對象 * @param builder 由spring注入這個(gè)對象,首先根據(jù)type注入(多個(gè)就取聲明@Primary的對象),否則根據(jù)name注入 * @return */ @Bean public LocalContainerEntityManagerFactoryBean secondEntityManagerFactory( EntityManagerFactoryBuilder builder) { return builder .dataSource(secondDataSource()) .packages("com.hdwang.entity.dbSecond") .persistenceUnit("secondDs") .build(); } /** * 事物管理對象 * @param secondEntityManagerFactory 實(shí)體管理工廠對象(按照名稱注入) * @return 平臺事物管理器 */ @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 會自動注入實(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 會自動注入實(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; } }
知識擴(kuò)展
1.如果采用傳統(tǒng)jpa方式,@EnableJpaRepositories無需配置,配置了也無影響。實(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,所以無需指明unitName,ds2必須指明。注入了準(zhǔn)確的entityManager,就可以直接拿來操作數(shù)據(jù)庫了。service層和上面一樣的,@Transactional("xxxManager")指明事物管理器即可!
2.采用jdbcTemplate方式,直接注入到Service層對象即可,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ù)庫操作方法均支持,包括事物。已經(jīng)經(jīng)過實(shí)踐證明了! 這是官方給出的最佳實(shí)踐,只是官方文檔沒寫細(xì)。導(dǎo)致整整坑了我?guī)滋?。至此,spring boot框架的使用就告一段落了!
以上這篇解決spring boot 1.5.4 配置多數(shù)據(jù)源的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot項(xiàng)目中同時(shí)操作多個(gè)數(shù)據(jù)庫的實(shí)現(xiàn)方法
在實(shí)際項(xiàng)目開發(fā)中可能存在需要同時(shí)操作兩個(gè)數(shù)據(jù)庫的場景,本文主要介紹了SpringBoot項(xiàng)目中同時(shí)操作多個(gè)數(shù)據(jù)庫的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03springMVC如何將controller中Model數(shù)據(jù)傳遞到j(luò)sp頁面
本篇文章主要介紹了springMVC如何將controller中Model數(shù)據(jù)傳遞到j(luò)sp頁面,具有一定的參考價(jià)值,有興趣的可以了解一下2017-07-07java基礎(chǔ)知識之FileInputStream流的使用
這篇文章主要介紹了java基礎(chǔ)知識之FileInputStream流的使用,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12SpringBoot整合BootStrap實(shí)戰(zhàn)
這篇文章主要介紹了SpringBoot整合BootStrap實(shí)戰(zhàn),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09Java后臺防止客戶端重復(fù)請求、提交表單實(shí)現(xiàn)原理
這篇文章主要介紹了Java后臺防止客戶端重復(fù)請求、提交表單實(shí)現(xiàn)原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12使用@CachePut?更新數(shù)據(jù)庫和更新緩存
這篇文章主要介紹了使用@CachePut?更新數(shù)據(jù)庫和更新緩存方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12