南京h5网站建设/百度本地惠生活推广
本文转自:SpringBoot2.0 jpa多数据源配置
随着Springboot升级到2.0,原来1.5.x的Jpa多数据源配置不能用了。现在总结一下Springboot2.0的jpa多数据源配置连接池还是用druid,但是不能用druid的starter了,譬如在1.5.x时用的是
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.6</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.6</version>
</dependency>
升级到2.0后,再用这个就会报错,因为一个AutoConfig的类缺失。那么要使用druid需要用下面的配置
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.6</version>
</dependency>
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.6</version>
</dependency>
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
注意log4j是druid强依赖的不能少,web是因为druid有web界面可以访问,也不能少。application.yml也有变化原来是这样的
spring: jpa: database: mysql show-sql: true hibernate: ddl-auto: update naming: strategy: org.hibernate.cfg.ImprovedNamingStrategy #命名策略,加分隔线"_"
主要变化就是naming这里,原来的ImprovedNamingStrategy不让用了,改成了下面的类
spring: datasource: primary: url: jdbc:mysql://localhost:3306/company?autoReconnect=true&useUnicode=true username: root password: root secondary: url: jdbc:mysql://localhost:3306/com1?autoReconnect=true&useUnicode=true username: root password: root jpa: database: mysql generate-ddl: true show-sql: true hibernate: ddl-auto: update hbm2ddl:auto: updatenaming: physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
双数据源:
先来配置druid的DataSource,这个类在新老版本里都能用,不需要变化。
package com.example.demo.druid;import com.alibaba.druid.pool.DruidDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import javax.sql.DataSource;
import java.sql.SQLException;/*** @author wuweifeng wrote on 2017/10/23.* 数据库连接属性配置*/
@ServletComponentScan
@Configuration
public class DruidDBConfig {private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);@Value("${spring.datasource.primary.url}")private String dbUrl1;@Value("${spring.datasource.primary.username}")private String username1;@Value("${spring.datasource.primary.password}")private String password1;@Value("${spring.datasource.secondary.username}")private String username2;@Value("${spring.datasource.secondary.password}")private String password2;@Value("${spring.datasource.secondary.url}")private String dbUrl2;@Value("com.mysql.jdbc.Driver")private String driverClassName;@Value("5")private int initialSize;@Value("5")private int minIdle;@Value("20")private int maxActive;@Value("60000")private int maxWait;/*** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒*/@Value("60000")private int timeBetweenEvictionRunsMillis;/*** 配置一个连接在池中最小生存的时间,单位是毫秒*/@Value("300000")private int minEvictableIdleTimeMillis;@Value("SELECT 1 FROM DUAL")private String validationQuery;@Value("true")private boolean testWhileIdle;@Value("false")private boolean testOnBorrow;@Value("false")private boolean testOnReturn;/*** 打开PSCache,并且指定每个连接上PSCache的大小*/@Value("true")private boolean poolPreparedStatements;@Value("20")private int maxPoolPreparedStatementPerConnectionSize;/*** 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙*/@Value("stat,wall,log4j")private String filters;/*** 通过connectProperties属性来打开mergeSql功能;慢SQL记录*/@Value("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500")private String connectionProperties;@Bean(name = "primaryDataSource")@Qualifier("primaryDataSource")public DataSource dataSource() {return getDruidDataSource(username1, password1, dbUrl1);}@Bean(name = "secondaryDataSource")@Qualifier("secondaryDataSource")@Primarypublic DataSource secondaryDataSource() {return getDruidDataSource(username2, password2, dbUrl2);}private DruidDataSource getDruidDataSource(String username, String password, String url) {DruidDataSource datasource = new DruidDataSource();datasource.setUrl(url);datasource.setUsername(username);datasource.setPassword(password);datasource.setDriverClassName(driverClassName);//configurationdatasource.setInitialSize(initialSize);datasource.setMinIdle(minIdle);datasource.setMaxActive(maxActive);datasource.setMaxWait(maxWait);datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);datasource.setValidationQuery(validationQuery);datasource.setTestWhileIdle(testWhileIdle);datasource.setTestOnBorrow(testOnBorrow);datasource.setTestOnReturn(testOnReturn);datasource.setPoolPreparedStatements(poolPreparedStatements);datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);try {datasource.setFilters(filters);} catch (SQLException e) {logger.error("druid configuration initialization filter : {0}", e);}datasource.setConnectionProperties(connectionProperties);return datasource;}
}
第一数据源:
package com.example.demo.druid;import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;/*** @author wuweifeng wrote on 2017/10/31.*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",transactionManagerRef = "transactionManagerPrimary",basePackages = {"com.example.demo.repository.primary"})
public class PrimaryConfig {@Resource@Qualifier("primaryDataSource")private DataSource primaryDataSource;@Primary@Bean(name = "entityManagerPrimary")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary(builder).getObject().createEntityManager();} @Resourceprivate JpaProperties jpaProperties;@Autowired(required = false)private PersistenceUnitManager persistenceUnitManager;private Map<String, Object> getVendorProperties() {return jpaProperties.getHibernateProperties(new HibernateSettings());}@Primary@Bean(name = "entityManagerFactoryBuilderPrimary")public EntityManagerFactoryBuilder entityManagerFactoryBuilderPrimary() {AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();return new EntityManagerFactoryBuilder(adapter, getVendorProperties(), persistenceUnitManager);}/*** 设置实体类所在位置*/@Primary@Bean(name = "entityManagerFactoryPrimary")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {return builder.dataSource(primaryDataSource).packages("com.example.demo.model.primary").persistenceUnit("primaryPersistenceUnit").properties(getVendorProperties()).build();}@Primary@Bean(name = "transactionManagerPrimary")public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());}}
注:这里需要设置 EntityManagerFactoryBuilder Bean,下面的方法中需要使用到。不添加的话,可能会报下面的错:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder' available:
expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1509)at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065)at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818)at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724)... 43 more
第二数据源:
package com.example.demo.druid;import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;/*** @author by wuweifeng on 2017/10/10.*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySecondary",transactionManagerRef = "transactionManagerSecondary",basePackages = {"com.example.demo.repository.secondary"})
public class SecondaryConfig {@Resource@Qualifier("secondaryDataSource")private DataSource secondaryDataSource;@Bean(name = "entityManagerSecondary")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactorySecondary(builder).getObject().createEntityManager();}@Resourceprivate JpaProperties jpaProperties;@Autowired(required = false)private PersistenceUnitManager persistenceUnitManager;private Map<String, Object> getVendorProperties() {return jpaProperties.getHibernateProperties(new HibernateSettings());}// 注意@Bean(name = "entityManagerFactoryBuilderSecondary")public EntityManagerFactoryBuilder entityManagerFactoryBuilderSecondary() {AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();return new EntityManagerFactoryBuilder(adapter, getVendorProperties(), persistenceUnitManager);}@Bean(name = "entityManagerFactorySecondary")public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) {return builder.dataSource(secondaryDataSource).packages("com.example.demo.model.secondary").persistenceUnit("secondaryPersistenceUnit").properties(getVendorProperties()).build();}@Bean(name = "transactionManagerSecondary")PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());}}
注意把里面的model包名和Repository包名替换为你自己的即可。
它与1.5.x版本的主要区别在于getVerdorProperties这个方法,原来的getHibernateProperties是传参数DataSource,现在是传参数HibernateSettings,
HibernateSettings类其实就是配置列名生成策略的,我们已经在yml里配置过了,这里直接new 一个空类过去就行了。
这样我们就完成了Springboot 2.0.0.M7的多数据源Jpa配置了。
还有一个地方需要提一下,Springboot2.0依赖了Hibernate5.2版本,1.5.x依赖的是Hibernate5.0.12版本,这两个版本在处理Id自增方面是不一样的。
在老版本里,我们定义了
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
public Long getId() { return id;
}
Id生成策略为Auto,那么默认会被转出Id自增。
在新版本里,Auto是不行的,不会自增,而且Hibernate会额外创建出来一个表来专门维护Id。可以自行尝试一下,会多出来一个表。
我们如果需要自增的Id,需要显式指定
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() { return id;
}