当前位置: 首页 > news >正文

南京h5网站建设/百度本地惠生活推广

南京h5网站建设,百度本地惠生活推广,同一个域名两个网站,自己做坑人网站的软件本文转自&#xff1a;SpringBoot2.0 jpa多数据源配置 随着Springboot升级到2.0&#xff0c;原来1.5.x的Jpa多数据源配置不能用了。现在总结一下Springboot2.0的jpa多数据源配置连接池还是用druid&#xff0c;但是不能用druid的starter了&#xff0c;譬如在1.5.x时用的是 <…

本文转自: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,

图1

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;  
}  
http://www.lbrq.cn/news/1432441.html

相关文章:

  • 电商app开发公司/网站关键词优化培训
  • 做集群网站/分销渠道
  • 开发手机网站的步骤/湖南网站推广公司
  • 网站开发英语翻译/seo排名赚app最新版本
  • 网站域名中请勿使用二级目录形式/网络科技公司
  • 支付网站怎么做/网络营销咨询服务
  • 长春专业网站推广/关键词提取工具app
  • 网站关键词进前三/今日重大军事新闻
  • 新乐网站制作价格/2023最新15件重大新闻
  • 做网站的联系方式/公司产品怎样网上推广
  • 网站建设价格/知乎seo
  • 做网站开发团队/游戏代理加盟平台
  • 天津做网站选择津坤科技c/友情链接可以随便找链接加吗
  • 网站菜单分类怎么做/各引擎收录查询
  • 成都专业建站推广公司/一键注册所有网站
  • 深圳网站建设公司的外文名是/竞价恶意点击器
  • 个人网站的重要性/全国免费发布信息平台
  • 怎么做用其他网站仿制一个网站/国内免费建网站
  • 团购产品 网站建设/seo优化有百度系和什么
  • 哪个网站可以做设计赚钱/做网站平台需要多少钱
  • 网站开发的缺点/西安seo教程
  • 想要接网站业务如何做/深圳关键词优化软件
  • 日本女做受网站BB/新闻稿营销
  • 百度商桥代码后网站上怎么不显示/百度风云榜各年度小说排行榜
  • 360免费wifi频繁掉线/google seo 优化教程
  • 网站建设投标书/360地图怎么添加商户
  • 书店建设网站/seo薪资水平
  • 紫色 网站/seo行业
  • 泉州晋江疫情最新情况/天津seo推广
  • 怎么黑进网站后台/关键词查询优化
  • 解锁AI大模型:Prompt工程全面解析
  • 人工智能与社会治理:从工具到生态的范式重构
  • Kafka生产者——提高生产者吞吐量
  • .Net4.0 WPF中实现下拉框搜索效果
  • Coze Studio 概览(十)--文档处理详细分析
  • 全球AI安全防护迈入新阶段:F5推出全新AI驱动型应用AI安全解决方案