spring:
datasource:
first:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://xx.xx.xx.xx:xx/xx?characterEncoding=utf8
driver-class-name: com.mysql.jdbc.Driver
username: xx
password: xx
#配置监控统计拦截的filters,去掉监控界面sql将无法统计,'wall'用于防火墙
filters: stat,wall,log4j
#最大活跃数
maxActive:
#初始化连接数
initialSize:
#最大连接等待超过时间
maxWait:
#打开PSCache,并且指定每个连接PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize:
#通过connectionProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=
minIdle:
timeBetweenEvictionRunsMillis:
minEvictableIdleTimeMillis:
validationQuery: select from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
sec:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://xx.xx.xx.xx:3306/xx?characterEncoding=utf8
driver-class-name: com.mysql.jdbc.Driver
username: xx
password: xx
#配置监控统计拦截的filters,去掉监控界面sql将无法统计,'wall'用于防火墙
filters: stat,wall,log4j
#最大活跃数
maxActive:
#初始化连接数
initialSize:
#最大连接等待超过时间
maxWait:
#打开PSCache,并且指定每个连接PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize:
#通过connectionProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=
minIdle:
timeBetweenEvictionRunsMillis:
minEvictableIdleTimeMillis:
validationQuery: select from dual
testWhileIdle: true
testOnBorrow: false
testOnReturn: false

配置文件

@ServletComponentScan
@Configuration
public class DatasourceConfiguration { private Logger logger = LoggerFactory.getLogger(DatasourceConfiguration.class); @Value("${spring.datasource.first.url}")
private String firstdevUrl;
@Value("${spring.datasource.first.username}")
private String firstUsername;
@Value("${spring.datasource.first.password}")
private String firstPassword; @Value("${spring.datasource.sec.url}")
private String secUrl;
@Value("${spring.datasource.sec.username}")
private String secUsername;
@Value("${spring.datasource.sec.password}")
private String secPassword; @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 = "secDatasource")
@Qualifier("secDatasource")
@ConfigurationProperties(prefix = "spring.datasource.sec")
public DataSource secDataSource() {
return getDruidDataSource(secUsername, secPassword, secUrl);
} @Bean(name = "firstDatasource")
@Qualifier("firstDatasource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return getDruidDataSource(firstUsername, firstPassword, firstUrl);
} 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); //configuration
datasource.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.ipinyou.mip.configuration;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter; /**
* 这样的方式不需要添加注解:@ServletComponentScan
* Created by Administrator on 2018/2/28.
*/
@Configuration
public class DruidConfiguration { @Bean
public ServletRegistrationBean statViewServlet(){
//创建Servlet,注册实体
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
//设置ip白名单
servletRegistrationBean.addInitParameter("allow","xx.xx.xx.xx");
//设置ip黑名单,如果deny和allow共同存在时,deny优先于allow
servletRegistrationBean.addInitParameter("deny","xx.xx.xx.xx");
//设置控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername","xxx");
servletRegistrationBean.addInitParameter("loginPassword","xxx");
//是否可以重置数据
servletRegistrationBean.addInitParameter("resetEnable","false");
return servletRegistrationBean;
} @Bean
public FilterRegistrationBean statFilter(){
//创建过滤器
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
//设置过滤器过滤路径
filterRegistrationBean.addUrlPatterns("/*");
//忽略过滤形式
filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}

设置数据源的过滤器

package com.ipinyou.mip.configuration;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
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; @Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary",
basePackages = {"xx.xx.xxx","xx.xx.xx"})//设置dao(repo)所在位置
public class JpaConfiguration { @Autowired
@Qualifier("firstDatasource")
private DataSource firstDataSource; @Primary
@Bean(name = "entityManagerFirst")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
} @Autowired
private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
} /**
* 设置实体类所在位置
*/
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(mipdevDataSource)
.packages("xx.xx.xx.xx")
.properties(getVendorProperties())
.persistenceUnit("firstManageFactory")
.properties(getVendorProperties())
.build();
} @Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}

firstJpaConfiguration

package com.ipinyou.mip.configuration;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired;
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; @Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactorySec",
transactionManagerRef = "transactionManagerSec",
basePackages = {"xx.xx.xx"})//设置dao(repo)所在位置
public class JpaSecConfiguration { @Autowired
@Qualifier("secDatasource")
private DataSource secDatasource; @Bean(name = "entityManagerAmp")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryAmp(builder).getObject().createEntityManager();
} @Autowired
private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() {
return jpaProperties.getHibernateProperties(new HibernateSettings());
} /**
* 设置实体类所在位置
*/
@Bean(name = "entityManagerFactorySec")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryAmp(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secDatasource)
.packages("xx.xx.xx")
.properties(getVendorProperties())
.persistenceUnit("secManageFactory")
.properties(getVendorProperties())
.build();
} @Bean(name = "transactionManagerSec")
public PlatformTransactionManager transactionManagerAmp(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySec(builder).getObject());
}
}

secJpaConfiguration

package com.ipinyou.mip.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate; @Configuration
@Import(DatasourceConfiguration.class)
public class JdbcTemplateConfiguration {
@Bean(name = "secJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("secDatasource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
} @Bean(name = "firstJdbcTemplate")
public JdbcTemplate threeJdbcTemplate(
@Qualifier("firstDatasource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}

JdbcTemplateConfiguration

/**
* 提供了一系列数据库查询方法
*
* @author guodong.zhang
*/
public class CommonDao<E, PK extends Serializable> { @PersistenceContext(unitName = "secManageFactory")
protected EntityManager em;
/**
* 相当于jdbctemplate的queryForlist 返回List<Map<String, Object>>
*
* @param sql
* @return
*/
public List<Map<String, Object>> queryForList(String sql) {
Query nativeQuery = em.createNativeQuery(sql);
nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
List<Map<String,Object>> resultList = nativeQuery.getResultList();
return resultList;
}
}

具体使用

如何使用多数据源,同时使用jpa和jdbctemplate的更多相关文章

  1. 五、spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate

    1.pom添加依赖 <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <group ...

  2. SpringBoot和druid数据源集成Jpa

    1.pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  3. springboot之jpa多数据源

    1.随着业务复杂程度的增加,我们在单一数据源上面的使用越来越不满足具体的业务逻辑以及实现了. 2.那么多数据源,比如多库多数据库等,我们在使用一个工程的时候多数据源的连接还是很有必要的,这里做一下记录 ...

  4. Spring Boot 2.x基础教程:Spring Data JPA的多数据源配置

    上一篇我们介绍了在使用JdbcTemplate来做数据访问时候的多数据源配置实现.接下来我们继续学习如何在使用Spring Data JPA的时候,完成多数据源的配置和使用. 添加多数据源的配置 先在 ...

  5. Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa

    多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...

  6. spring boot jpa 多数据源配置

    在实际项目中往往会使用2个数据源,这个时候就需要做额外的配置了.下面的配置在2.0.1.RELEASE 测试通过 1.配置文件 配置两个数据源 spring.datasource.url=jdbc:m ...

  7. 六:SpringBoot-引入JdbcTemplate,和多数据源配置

    SpringBoot-引入JdbcTemplate,和多数据源配置 1.JdbcTemplate对象 1.1 JdbcTemplate核心方法 2.SpringBoot中使用JDBCTemplate ...

  8. JPA相关知识

    这篇文章是摘自Patrick Linskey的一篇文章,主要是关于JPA相关内容的问答,相信JPA面试会碰到很多这里面的问题 问题:EJB专家团队是如何摆脱事务描述符的? 回答:在会话bean和消息驱 ...

  9. 学习Spring Boot:(二十四)多数据源配置与使用

    前言 随着业务量增大,可能有些业务不是放在同一个数据库中,所以系统有需求使用多个数据库完成业务需求,我们需要配置多个数据源,从而进行操作不同数据库中数据. 正文 JdbcTemplate 多数据源 配 ...

随机推荐

  1. 软件设计之Deep Module(深模块)

    类是不是越小越好?最近在读John Ousterhout的<A Philosophy of Software Design>,感到作者文笔流畅,书中内容具有启发性.这里摘要一部分内容,以供 ...

  2. Git拉取、提交、迁出、合并、删除分之命令

    #拉取代码 git clone -b 分之名称 git地址 #提交代码 git add . //:注释,if是第一次提交: $ git add --all . (请注意后面有个英文点(表示是当前目录) ...

  3. dispatch_barrier_async--屏障是一个同步点

    Discussion Calls to this function always return immediately after the block has been submitted and n ...

  4. vue.js 跳转同一页面,传不同值,组件监听路由

    watch: { '$route' () { this.type = this.$route.params.type this.loadData() } },

  5. 监控redis

    [4ajr@redis1 scripts]$ cat redismonitor.sh #!/bin/bash #想要什么监控项再添加 rediscli="/soft/redis/bin/re ...

  6. 回顾servlet生命周期(代码测试),读取初始化参数

    servlet生命周期 为简洁,本例使用注解方式来测试,代码部分很简单,只需要新建一个serlet,继承自HttpServlet,重写init,doGet,doPost,destory方法即可,使用注 ...

  7. JS&Java实现常见算法面试题

    Github上的算法repo地址:https://github.com/qcer/Algo-Practice (如果你觉得有帮助,可以给颗星星收藏之~~~) 一.Java实现部分 参见随笔分类的算法部 ...

  8. Python第一天:你必须要知道的Python擅长领域以及各种重点学习框架(包含Python在世界上的应用)

    目录 Python5大擅长领域 WEB开发 网络编程 科学运算 GUI图形开发 运维自动化 Python在世界上的知名应用 国外 谷歌 CIA NASA YouTube Dropbox Instagr ...

  9. docker 小技巧 列出所有容器的IP地址

    命令如下: [root@localhost ~]# docker inspect --format='{{.Name}} - {{range .NetworkSettings.Networks}}{{ ...

  10. Firefox 中出现的 “Network Protocol Error”怎么办

    Mozilla Firefox 多年来一直是我的默认 Web 浏览器,我每天用它来进行日常网络活动,例如访问邮件,浏览喜欢的网站等.今天,我在使用 Firefox 时遇到了一个奇怪的错误.我试图在 R ...