日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

13.SpringBoot学习(十三)——JDBC之 Spring Boot Jpa多数据源

發布時間:2023/12/18 javascript 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 13.SpringBoot学习(十三)——JDBC之 Spring Boot Jpa多数据源 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.簡介

1.1 概述

在實際項目中一般是一個數據源,但是在某些特殊場景可能需要多個數據源,這里以 spring boot jpa 為例演示一下多數據源的配置和使用。

2.演示環境

  • JDK 1.8.0_201
  • Spring Boot 2.2.0.RELEASE
  • 構建工具(apache maven 3.6.3)
  • 開發工具(IntelliJ IDEA )
  • 3.演示代碼

    3.1 代碼說明

    配置兩個數據源,分別是 masterDataSource 和 slaveDataSource,它們由兩個配置類 MasterConfiguration 和 SlaveConfiguration 來加載,分別掃描不同路徑下的 repository。最后通過測試類來調用。

    3.2 代碼結構

    3.3 maven 依賴

    <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> </dependencies>

    3.4 配置文件

    application.properties

    # master 數據源 spring.datasource.master.jdbc-url=jdbc:mysql://172.16.11.125:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.master.username=root spring.datasource.master.password=123456 spring.datasource.master.driver-class-name=com.mysql.cj.jdbc.Driver# slave 數據源 spring.datasource.slave.jdbc-url=jdbc:mysql://172.16.11.125:3306/test_jpa?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.slave.username=root spring.datasource.slave.password=123456 spring.datasource.slave.driver-class-name=com.mysql.cj.jdbc.Driver# 打印sql、自動建表、格式化sql spring.jpa.show-sql=true spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto=create spring.jpa.properties.hibernate.format_sql=true spring.jpa.properties.hibernate.hbm2ddl.auto=create spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect# 日志打印 logging.level.root=INFO logging.level.org.hibernate=INFO logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE logging.level.org.hibernate.type.descriptor.sql.BasicExtractor=TRACE logging.level.com.soulballad.usage=DEBUG

    3.5 java代碼

    UserModel.java

    @Entity @Table(name = "t_user") public class UserModel {@Id@GeneratedValueprivate Long id;@Column(nullable = false, unique = true, length = 32)private String name;@Column(nullable = false)private Integer age;@Column(length = 32)private String birthday;private String address;@Column(nullable = false, length = 16)private String phone;public UserModel() {}public UserModel(String name, Integer age, String birthday, String address, String phone) {this.name = name;this.age = age;this.birthday = birthday;this.address = address;this.phone = phone;}// get&set&toString }

    MasterUserRepository.java

    @Repository public interface MasterUserRepository extends JpaRepository<UserModel, Long> {UserModel findByName(String name);UserModel findByPhone(String phone); }

    SlaveUserRepository.java

    @Repository public interface SlaveUserRepository extends JpaRepository<UserModel, Long> {UserModel findByName(String name);UserModel findByPhone(String phone); }

    DataSourceConfig.java

    @Configuration public class DataSourceConfig {@Autowiredprivate JpaProperties jpaProperties;@Autowiredprivate HibernateProperties hibernateProperties;@Primary@Bean(name = "masterDataSource")@ConfigurationProperties(prefix = "spring.datasource.master")public DataSource masterDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "slaveDataSource")@ConfigurationProperties(prefix = "spring.datasource.slave")public DataSource slaveDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "vendorProperties")public Map<String, Object> getVendorProperties() {return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());} }

    MasterConfiguration.java

    @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryMaster",transactionManagerRef = "transactionManagerMaster",basePackages = "com.soulballad.usage.springboot.repository.master") // repo(dao)所在位置 public class MasterConfiguration {@Autowired@Qualifier("masterDataSource")private DataSource masterDataSource;@Autowired@Qualifier("vendorProperties")private Map<String, Object> vendorProperties;@Primary@Bean(name = "entityManagerFactoryMaster")public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {return builder.dataSource(masterDataSource).properties(vendorProperties).packages("com.soulballad.usage.springboot.model") // 實體類所在位置.persistenceUnit("masterPersistenceUnit").build();}@Primary@Bean(name = "entityManagerMaster")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryBean(builder).getObject().createEntityManager();}@Primary@Bean(name = "transactionManagerMaster")PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());} }

    SlaveConfiguration.java

    @Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "entityManageFactorySlave",transactionManagerRef = "transactionManagerSlave",basePackages = "com.soulballad.usage.springboot.repository.slave") public class SlaveConfiguration {@Autowired@Qualifier("slaveDataSource")private DataSource slaveDataSource;@Autowired@Qualifier("vendorProperties")private Map<String, Object> vendorProperties;@Bean(name = "entityManageFactorySlave")public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {return builder.dataSource(slaveDataSource).properties(vendorProperties).packages("com.soulballad.usage.springboot.model").persistenceUnit("slavePersistenceUnit").build();}@Bean(name = "entityManageSlave")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryBean(builder).getObject().createEntityManager();}@Bean(name = "transactionManagerSlave")PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());} }

    測試類

    UserRepositoryTest.java

    @RunWith(SpringRunner.class) @SpringBootTest public class UserRepositoryTest {@Autowiredprivate MasterUserRepository masterUserRepository;@Autowiredprivate SlaveUserRepository slaveUserRepository;@Beforepublic void save() {UserModel user1 = new UserModel("zhangsan", 20, "2000-01-01", "shenzhen", "13888888888");UserModel user2 = new UserModel("lisi", 21, "1999-01-01", "shanghai", "13777777777");UserModel user3 = new UserModel("wangwu", 22, "1998-01-01", "beijing", "13666666666");UserModel user4 = new UserModel("zhaoliu", 23, "1997-01-01", "guangzhou", "13555555555");UserModel user5 = new UserModel("sunqi", 24, "1996-01-01", "wuhan", "13444444444");List<UserModel> userList = Arrays.asList(user1, user2, user3, user4, user5);masterUserRepository.saveAll(userList);slaveUserRepository.saveAll(userList);}@Testpublic void test_findByName() {UserModel masterUser = masterUserRepository.findByName("zhangsan");UserModel slaveUser = slaveUserRepository.findByName("zhangsan");System.err.println(masterUser);System.err.println(slaveUser);}@Testpublic void test_findUserByPhone() {UserModel masterUser = masterUserRepository.findByPhone("13666666666");UserModel slaveUser = slaveUserRepository.findByPhone("13666666666");System.err.println(masterUser);System.err.println(slaveUser);} }

    3.6 git 地址

    spring-boot/spring-boot-06-jdbc/spring-boot-multi-datasource

    4.效果展示

    啟動 SpringBootMultiDatasourceApplication.main 方法,執行測試類 UserRepositoryTest 中方法,觀察結果是否符合預期。

    UserRepositoryTest#test_findByName

    UserRepositoryTest#test_findByName

    總結

    以上是生活随笔為你收集整理的13.SpringBoot学习(十三)——JDBC之 Spring Boot Jpa多数据源的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。