当前位置:   article > 正文

SpringBoot2.0 jpa多数据源配置_jpa 多数据源 连接池配置不会继承

jpa 多数据源 连接池配置不会继承

随着Springboot升级到2.0,原来1.5.x的Jpa多数据源配置不能用了。现在总结一下Springboot2.0的jpa多数据源配置

连接池还是用druid,但是不能用druid的starter了,譬如在1.5.x时用的是

 

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>druid-spring-boot-starter</artifactId>
  4. <version>1.1.6</version>
  5. </dependency>

升级到2.0后,再用这个就会报错,因为一个AutoConfig的类缺失。那么要使用druid需要用下面的配置

  1. <!--druid begin-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid-spring-boot-starter</artifactId>
  5. <version>1.1.10</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>log4j</groupId>
  9. <artifactId>log4j</artifactId>
  10. <version>1.2.17</version>
  11. </dependency>
  12. <!--druid end-->

 

注意log4j是druid强依赖的不能少,web是因为druid有web界面可以访问,也不能少。

 

 

application.yml也有变化

原来是这样的

 

  1. spring:
  2. jpa:
  3. database: mysql
  4. show-sql: true
  5. hibernate:
  6. ddl-auto: update
  7. naming:
  8. strategy: org.hibernate.cfg.ImprovedNamingStrategy #命名策略,加分隔线"_"

主要变化就是naming这里,原来的ImprovedNamingStrategy不让用了,改成了下面的类

  1. spring:
  2. datasource:
  3. primary:
  4. url: jdbc:mysql://localhost:3306/company?autoReconnect=true&useUnicode=true
  5. username: root
  6. password: root
  7. secondary:
  8. url: jdbc:mysql://localhost:3306/com1?autoReconnect=true&useUnicode=true
  9. username: root
  10. password: root
  11. jpa:
  12. database: mysql
  13. generate-ddl: true
  14. show-sql: true
  15. hibernate:
  16. ddl-auto: update
  17. naming:
  18. physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy

 

 

 

双数据源:

 

 

先来配置druid的DataSource,这个类在新老版本里都能用,不需要变化。

  1. package com.example.demo.druid;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Qualifier;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.boot.web.servlet.ServletComponentScan;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.context.annotation.Primary;
  11. import javax.sql.DataSource;
  12. import java.sql.SQLException;
  13. /**
  14. * @author wuweifeng wrote on 2017/10/23.
  15. * 数据库连接属性配置
  16. */
  17. @ServletComponentScan
  18. @Configuration
  19. public class DruidDBConfig {
  20. private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
  21. @Value("${spring.datasource.primary.url}")
  22. private String dbUrl1;
  23. @Value("${spring.datasource.primary.username}")
  24. private String username1;
  25. @Value("${spring.datasource.primary.password}")
  26. private String password1;
  27. @Value("${spring.datasource.secondary.username}")
  28. private String username2;
  29. @Value("${spring.datasource.secondary.password}")
  30. private String password2;
  31. @Value("${spring.datasource.secondary.url}")
  32. private String dbUrl2;
  33. @Value("com.mysql.jdbc.Driver")
  34. private String driverClassName;
  35. @Value("5")
  36. private int initialSize;
  37. @Value("5")
  38. private int minIdle;
  39. @Value("20")
  40. private int maxActive;
  41. @Value("60000")
  42. private int maxWait;
  43. /**
  44. * 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  45. */
  46. @Value("60000")
  47. private int timeBetweenEvictionRunsMillis;
  48. /**
  49. * 配置一个连接在池中最小生存的时间,单位是毫秒
  50. */
  51. @Value("300000")
  52. private int minEvictableIdleTimeMillis;
  53. @Value("SELECT 1 FROM DUAL")
  54. private String validationQuery;
  55. @Value("true")
  56. private boolean testWhileIdle;
  57. @Value("false")
  58. private boolean testOnBorrow;
  59. @Value("false")
  60. private boolean testOnReturn;
  61. /**
  62. * 打开PSCache,并且指定每个连接上PSCache的大小
  63. */
  64. @Value("true")
  65. private boolean poolPreparedStatements;
  66. @Value("20")
  67. private int maxPoolPreparedStatementPerConnectionSize;
  68. /**
  69. * 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  70. */
  71. @Value("stat,wall,log4j")
  72. private String filters;
  73. /**
  74. * 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  75. */
  76. @Value("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500")
  77. private String connectionProperties;
  78. @Bean(name = "primaryDataSource")
  79. @Qualifier("primaryDataSource")
  80. public DataSource dataSource() {
  81. return getDruidDataSource(username1, password1, dbUrl1);
  82. }
  83. @Bean(name = "secondaryDataSource")
  84. @Qualifier("secondaryDataSource")
  85. @Primary
  86. public DataSource secondaryDataSource() {
  87. return getDruidDataSource(username2, password2, dbUrl2);
  88. }
  89. private DruidDataSource getDruidDataSource(String username, String password, String url) {
  90. DruidDataSource datasource = new DruidDataSource();
  91. datasource.setUrl(url);
  92. datasource.setUsername(username);
  93. datasource.setPassword(password);
  94. datasource.setDriverClassName(driverClassName);
  95. //configuration
  96. datasource.setInitialSize(initialSize);
  97. datasource.setMinIdle(minIdle);
  98. datasource.setMaxActive(maxActive);
  99. datasource.setMaxWait(maxWait);
  100. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  101. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  102. datasource.setValidationQuery(validationQuery);
  103. datasource.setTestWhileIdle(testWhileIdle);
  104. datasource.setTestOnBorrow(testOnBorrow);
  105. datasource.setTestOnReturn(testOnReturn);
  106. datasource.setPoolPreparedStatements(poolPreparedStatements);
  107. datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  108. try {
  109. datasource.setFilters(filters);
  110. } catch (SQLException e) {
  111. logger.error("druid configuration initialization filter : {0}", e);
  112. }
  113. datasource.setConnectionProperties(connectionProperties);
  114. return datasource;
  115. }
  116. }

第一数据源:

  1. package com.maimeng.pingtai.maimengoperate.db;
  2. import org.springframework.beans.factory.annotation.Qualifier;
  3. import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.context.annotation.Primary;
  7. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  8. import org.springframework.orm.jpa.JpaTransactionManager;
  9. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  10. import org.springframework.transaction.PlatformTransactionManager;
  11. import org.springframework.transaction.annotation.EnableTransactionManagement;
  12. import javax.annotation.Resource;
  13. import javax.persistence.EntityManager;
  14. import javax.sql.DataSource;
  15. import java.util.Properties;
  16. /**
  17. * Created by Administrator on 2017/8/11.
  18. * <p>
  19. * 数据源一
  20. */
  21. @Configuration
  22. @EnableTransactionManagement
  23. @EnableJpaRepositories(
  24. entityManagerFactoryRef = "entityManagerFactoryPrimary",
  25. transactionManagerRef = "transactionManagerPrimary",
  26. basePackages = {"com.maimeng.pingtai.maimengoperate.repository.one"})
  27. public class OneConfig {
  28. @Resource
  29. @Qualifier("primaryDataSource")
  30. private DataSource primaryDataSource;
  31. @Primary
  32. @Bean(name = "entityManagerPrimary")
  33. public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
  34. return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
  35. }
  36. @Resource
  37. private Properties jpaProperties;
  38. /**
  39. * 设置实体类所在位置
  40. */
  41. @Primary
  42. @Bean(name = "entityManagerFactoryPrimary")
  43. public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
  44. LocalContainerEntityManagerFactoryBean entityManagerFactory = builder
  45. .dataSource(primaryDataSource)
  46. .packages("com.maimeng.pingtai.maimengoperate.entity.one")
  47. .persistenceUnit("primaryPersistenceUnit")
  48. .build();
  49. entityManagerFactory.setJpaProperties(jpaProperties);
  50. return entityManagerFactory;
  51. }
  52. @Primary
  53. @Bean(name = "transactionManagerPrimary")
  54. public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
  55. return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
  56. }
  57. }

 

第二数据源:

  1. package com.maimeng.pingtai.maimengoperate.db;
  2. import org.springframework.beans.factory.annotation.Qualifier;
  3. import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
  7. import org.springframework.orm.jpa.JpaTransactionManager;
  8. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
  9. import org.springframework.transaction.PlatformTransactionManager;
  10. import org.springframework.transaction.annotation.EnableTransactionManagement;
  11. import javax.annotation.Resource;
  12. import javax.persistence.EntityManager;
  13. import javax.sql.DataSource;
  14. import java.util.Properties;
  15. /**
  16. * Created by Administrator on 2017/8/11.
  17. * <p>
  18. * 数据源一
  19. */
  20. @Configuration
  21. @EnableTransactionManagement
  22. @EnableJpaRepositories(
  23. entityManagerFactoryRef = "entityManagerFactorySecondary",
  24. transactionManagerRef = "transactionManagerSecondary",
  25. basePackages = {"com.maimeng.pingtai.maimengoperate.repository.two"}) //设置Repository所在位置
  26. public class TwoConfig {
  27. @Resource
  28. @Qualifier("secondaryDataSource")
  29. private DataSource secondaryDataSource;
  30. @Resource
  31. private Properties jpaProperties;
  32. @Bean(name = "entityManagerSecondary")
  33. public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
  34. return entityManagerFactorySecondary(builder).getObject().createEntityManager();
  35. }
  36. @Bean(name = "entityManagerFactorySecondary")
  37. public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {
  38. LocalContainerEntityManagerFactoryBean entityManagerFactory
  39. = builder
  40. .dataSource(secondaryDataSource)
  41. .packages("com.maimeng.pingtai.maimengoperate.entity.two")//设置实体类所在位置
  42. .persistenceUnit("secondaryPersistenceUnit")//持久化单元创建一个默认即可,多个便要分别命名
  43. .build();
  44. entityManagerFactory.setJpaProperties(jpaProperties);
  45. return entityManagerFactory;
  46. }
  47. @Bean(name = "transactionManagerSecondary")
  48. public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
  49. return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
  50. }
  51. }


注意把里面的model包名和Repository包名替换为你自己的即可。

 

这样我们就完成了Springboot 2.*的多数据源Jpa配置了。

还有一个地方需要提一下,Springboot2.0依赖了Hibernate5.2版本,1.5.x依赖的是Hibernate5.0.12版本,这两个版本在处理Id自增方面是不一样的。

在老版本里,我们定义了

  1. @Id
  2. @GeneratedValue(strategy = GenerationType.AUTO)
  3. @Column(name = "id")
  4. public Long getId() {
  5. return id;
  6. }

Id生成策略为Auto,那么默认会被转出Id自增。

 

在新版本里,Auto是不行的,不会自增,而且Hibernate会额外创建出来一个表来专门维护Id。可以自行尝试一下,会多出来一个表。

我们如果需要自增的Id,需要显式指定

 

  1. @Id
  2. @GeneratedValue(strategy = GenerationType.IDENTITY)
  3. @Column(name = "id")
  4. public Long getId() {
  5. return id;
  6. }

 

 

 

 

 

 

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

闽ICP备14008679号