当前位置:   article > 正文

避坑版:springboot+JPA如何配多种数据源(postgresql+mysql)_jpa多数据源

jpa多数据源

注意: JPA和mybatis是不同的持久层,各自特点独特,

与mybatis相比,JPA需要考虑对数据源的映射和操作,

通常我们设置在项目启动时,JPA就会根据设置去创建或者更新表,

因此不能像mybayis那样等到调用时再去告诉方法用哪个数据源,

JPA需要一开始就设定好repository和entity所对应的数据源,

在下列文件repository里你可以看到相关设置;

坑,请注意,网上有很多的JPA配多种数据源,但是他们都缺失一点,连方言都没有设置,有的压根不知道这回事,要知道,JPA对不同的数据库以及数据库不同版本有不同的数据方言,

此处一定要手动去设置各自不同的方言,在我的数据源设置那你可以看到手动设置方言,如果你不设置,那除非你把ddl_auto设置为none,可那样的话,项目才开始搭建,你就把JPA的特性干掉了一部分,多尴尬

application.properties数据源配置文件

  1. #pg\u5E93
  2. spring.pg.datasource.show-sql=true
  3. spring.jpa.properties.hibernate.pg-dialect=org.hibernate.dialect.PostgreSQLDialect
  4. spring.pg.datasource.hibernate.ddl-auto=update
  5. spring.pg.datasource.platform=postgres
  6. spring.pg.datasource.jdbc-url=jdbc:postgresql://localhost:7017/ddb
  7. spring.pg.datasource.username=ddb_user
  8. spring.pg.datasource.password=FSCn2qS8
  9. spring.pg.datasource.driver-class-name=org.postgresql.Driver
  10. #mysql
  11. spring.mysql.datasource.show-sql=true
  12. spring.jpa.properties.hibernate.mysql-dialect=org.hibernate.dialect.MySQL8Dialect
  13. spring.mysql.datasource.hibernate.ddl-auto=update
  14. spring.mysql.datasource.jdbc-url=jdbc:mysql://localhost:3306/testData?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8&allowPublicKeyRetrieval=true
  15. spring.mysql.datasource.username=root
  16. spring.mysql.datasource.password=666666
  17. spring.mysql.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
DataSourceConfig.java 数据源实例
  1. package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;
  2. /**
  3. * @Author:
  4. * @Description:
  5. * @Date: 2021/8/28 13:58
  6. * @Modified By:
  7. * @since v1.0.1
  8. */
  9. import org.springframework.beans.factory.annotation.Qualifier;
  10. import org.springframework.boot.context.properties.ConfigurationProperties;
  11. import org.springframework.boot.jdbc.DataSourceBuilder;
  12. import org.springframework.context.annotation.Bean;
  13. import org.springframework.context.annotation.Configuration;
  14. import org.springframework.context.annotation.Primary;
  15. import javax.sql.DataSource;
  16. /**
  17. * 数据源的配置
  18. */
  19. @Configuration
  20. public class DataSourceConfig {
  21. @Bean(name = "pgDataSource")
  22. @Qualifier("pgDataSource")
  23. @ConfigurationProperties(prefix = "spring.pg.datasource")
  24. @Primary
  25. public DataSource pgDataSource() {
  26. return DataSourceBuilder.create().build();
  27. }
  28. @Bean(name = "mysqlDataSource")
  29. @Qualifier("mysqlDataSource")
  30. @ConfigurationProperties(prefix = "spring.mysql.datasource")
  31. public DataSource mysqlDataSource() {
  32. return DataSourceBuilder.create().build();
  33. }
  34. }
PgConfig.java   pg数据源的配置
  1. package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;
  2. /**
  3. * @Author:
  4. * @Description:
  5. * @Date: 2021/8/28 13:58
  6. * @Modified By:
  7. * @since v1.0.1
  8. */
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
  13. import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
  14. import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
  15. import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
  16. import org.springframework.context.annotation.Bean;
  17. import org.springframework.context.annotation.Configuration;
  18. import org.springframework.context.annotation.Primary;
  19. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  20. import org.springframework.orm.jpa.JpaTransactionManager;
  21. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  22. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  23. import org.springframework.transaction.PlatformTransactionManager;
  24. import org.springframework.transaction.annotation.EnableTransactionManagement;
  25. import javax.persistence.EntityManager;
  26. import javax.sql.DataSource;
  27. import java.util.HashMap;
  28. import java.util.Map;
  29. /**
  30. * 数据源一
  31. */
  32. @Configuration
  33. @EnableTransactionManagement
  34. @EnableJpaRepositories(
  35. entityManagerFactoryRef = "entityManagerFactoryPg",
  36. transactionManagerRef = "transactionManagerPg",
  37. basePackages = {
  38. "xx.xx.xx.repository"
  39. }) //设置Repository所在位置
  40. public class PgConfig {
  41. @Autowired
  42. @Qualifier("pgDataSource")
  43. private DataSource pgDataSource;
  44. //方言
  45. @Value("${spring.jpa.properties.hibernate.pg-dialect}")
  46. private String pgDialect;
  47. //表操作
  48. @Value("${spring.pg.datasource.hibernate.ddl-auto}")
  49. private String pg_ddl_auto;
  50. @Value("${spring.pg.datasource.show-sql}")
  51. private String pg_show_sql;
  52. @Primary
  53. @Bean(name = "entityManagerPg")
  54. public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
  55. return entityManagerFactoryPg(builder).getObject().createEntityManager();
  56. }
  57. @Primary
  58. @Bean(name = "entityManagerFactoryPg")
  59. public LocalContainerEntityManagerFactoryBean entityManagerFactoryPg(EntityManagerFactoryBuilder builder) {
  60. LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  61. em.setDataSource(pgDataSource);
  62. em.setPackagesToScan(new String[] { "com.hikvision.aries.jc.ihswfld.web.modules.repository.entity" });
  63. HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
  64. em.setJpaVendorAdapter(vendorAdapter);
  65. HashMap<String, Object> properties = new HashMap<>();
  66. properties.put("hibernate.hbm2ddl.auto",pg_ddl_auto);
  67. properties.put("hibernate.dialect",pgDialect);
  68. properties.put("hibernate.show_sql",pg_show_sql);
  69. em.setJpaPropertyMap(properties);
  70. return em;
  71. }
  72. @Primary
  73. @Bean(name = "transactionManagerPg")
  74. public PlatformTransactionManager transactionManagerPg(EntityManagerFactoryBuilder builder) {
  75. return new JpaTransactionManager(entityManagerFactoryPg(builder).getObject());
  76. }
  77. }
MysqlConfig.java 数据源的配置
  1. package com.hikvision.aries.jc.ihswfld.web.modules.dbconfig;
  2. /**
  3. * @Author:
  4. * @Description:
  5. * @Date: 2021/8/28 13:59
  6. * @Modified By:
  7. * @since v1.0.1
  8. */
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.beans.factory.annotation.Qualifier;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
  13. import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
  14. import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
  15. import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
  16. import org.springframework.context.annotation.Bean;
  17. import org.springframework.context.annotation.Configuration;
  18. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  19. import org.springframework.orm.jpa.JpaTransactionManager;
  20. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  21. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
  22. import org.springframework.transaction.PlatformTransactionManager;
  23. import org.springframework.transaction.annotation.EnableTransactionManagement;
  24. import javax.persistence.EntityManager;
  25. import javax.sql.DataSource;
  26. import java.util.HashMap;
  27. import java.util.Map;
  28. /**
  29. * 数据源二
  30. */
  31. @Configuration
  32. @EnableTransactionManagement
  33. @EnableJpaRepositories(
  34. entityManagerFactoryRef = "entityManagerFactoryMysql",
  35. transactionManagerRef = "transactionManagerMysql",
  36. basePackages = {
  37. "xx.xx.xx.mysqlRepository"
  38. }) //设置Repository所在位置,两个数据库对应的repository和实体类需要不同的路径
  39. public class MysqlConfig {
  40. @Autowired
  41. @Qualifier("mysqlDataSource")
  42. private DataSource mysqlDataSource;
  43. //方言
  44. @Value("${spring.jpa.properties.hibernate.mysql-dialect}")
  45. private String mysqlDialect;
  46. //表操作
  47. @Value("${spring.mysql.datasource.hibernate.ddl-auto}")
  48. private String mysq_ddl_auto;
  49. @Value("${spring.mysql.datasource.show-sql}")
  50. private String mysql_show_sql;
  51. @Bean(name = "entityManagerMysql")
  52. public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
  53. return entityManagerFactoryMysql(builder).getObject().createEntityManager();
  54. }
  55. @Bean(name = "entityManagerFactoryMysql")
  56. public LocalContainerEntityManagerFactoryBean entityManagerFactoryMysql(EntityManagerFactoryBuilder builder) {
  57. LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  58. em.setDataSource(mysqlDataSource);
  59. em.setPackagesToScan(new String[] { "com.hikvision.aries.jc.ihswfld.web.modules.mysqlRepository.entity" });
  60. HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
  61. em.setJpaVendorAdapter(vendorAdapter);
  62. HashMap<String, Object> properties = new HashMap<>();
  63. properties.put("hibernate.hbm2ddl.auto",mysq_ddl_auto);
  64. properties.put("hibernate.dialect",mysqlDialect);
  65. properties.put("hibernate.show_sql",mysql_show_sql);
  66. em.setJpaPropertyMap(properties);
  67. return em;
  68. }
  69. //用来作为数据库事务回滚的限定词
  70. //@Transactional(rollbackFor = OAPMException.class, value = "transactionManagerMysql")
  71. //事务管理器
  72. @Bean(name = "transactionManagerMysql")
  73. PlatformTransactionManager transactionManagerMysql(EntityManagerFactoryBuilder builder) {
  74. return new JpaTransactionManager(entityManagerFactoryMysql(builder).getObject());
  75. }
  76. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/954911
推荐阅读
相关标签
  

闽ICP备14008679号