如何使用多数据源,同时使用jpa和jdbctemplate
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的更多相关文章
- 五、spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate
1.pom添加依赖 <!-- spring data jpa,会注入tomcat jdbc pool/hibernate等 --> <dependency> <group ...
- SpringBoot和druid数据源集成Jpa
1.pom文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...
- springboot之jpa多数据源
1.随着业务复杂程度的增加,我们在单一数据源上面的使用越来越不满足具体的业务逻辑以及实现了. 2.那么多数据源,比如多库多数据库等,我们在使用一个工程的时候多数据源的连接还是很有必要的,这里做一下记录 ...
- Spring Boot 2.x基础教程:Spring Data JPA的多数据源配置
上一篇我们介绍了在使用JdbcTemplate来做数据访问时候的多数据源配置实现.接下来我们继续学习如何在使用Spring Data JPA的时候,完成多数据源的配置和使用. 添加多数据源的配置 先在 ...
- Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa
多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...
- spring boot jpa 多数据源配置
在实际项目中往往会使用2个数据源,这个时候就需要做额外的配置了.下面的配置在2.0.1.RELEASE 测试通过 1.配置文件 配置两个数据源 spring.datasource.url=jdbc:m ...
- 六:SpringBoot-引入JdbcTemplate,和多数据源配置
SpringBoot-引入JdbcTemplate,和多数据源配置 1.JdbcTemplate对象 1.1 JdbcTemplate核心方法 2.SpringBoot中使用JDBCTemplate ...
- JPA相关知识
这篇文章是摘自Patrick Linskey的一篇文章,主要是关于JPA相关内容的问答,相信JPA面试会碰到很多这里面的问题 问题:EJB专家团队是如何摆脱事务描述符的? 回答:在会话bean和消息驱 ...
- 学习Spring Boot:(二十四)多数据源配置与使用
前言 随着业务量增大,可能有些业务不是放在同一个数据库中,所以系统有需求使用多个数据库完成业务需求,我们需要配置多个数据源,从而进行操作不同数据库中数据. 正文 JdbcTemplate 多数据源 配 ...
随机推荐
- 第三节 pandas续集
import pandas as pd from pandas import Series from pandas import DataFrame import numpy as np 一 创建多层 ...
- Windows操作系统分类
Windows主要有桌面版和服务器版.移动版三个版本 桌面版现在主流是WindowsXP.WindowsVista.Windows7.Windows8.Windows10 其中WindowsXP已经被 ...
- HTML5 canvas clearRect() 方法
浏览器支持 Internet Explorer 9.Firefox.Opera.Chrome 以及 Safari 支持 clearRect() 方法. 注释:Internet Explorer 8 或 ...
- equals方法相关总结
先说一下Object类吧: 这是一个号称为祖宗类的东西,是所有类的父类,也是唯一一个没有父类的类. 接口不继承object类 并且Object类存在于java的lang包中,我们都知道存在于lang包 ...
- day9-基础函数的学习(四)
这几天一直赶着写写作业,博客的书写又落下了,要加油鸭,开写 今日份目录 1.内置函数 2.递归函数 开始今日份总结 1.内置函数 内置函数就是python内部包含的函数,总计有68种,不过有些事真的天 ...
- SpringBoot前端模板
Springboot支持thymeleaf.freemarker.JSP,但是官方不建议使用JSP,因为有些功能会受限制,这里介绍thymeleaf和freemarker. 一.thymeleaf模板 ...
- [JLOI2015]骗我呢
[JLOI2015]骗我呢 Tags:题解 作业部落 评论地址 TAG:数学,DP 题意 骗你呢 求满足以下条件的\(n*m\)的矩阵的个数对\(10^9+7\)取模 对于矩阵中的第\(i\)行第\( ...
- OpenStack-Keystone(2)
一. Keystone 概述 管理用户及其权限 维护OpenStack Services的Endpoint Authentication(认证)和 Authorization(授权) 1.验证用户 验 ...
- XP_CMDSHELL 执行命令添加 windows 用户的方法
1. 之前看过不少文档 可以使用 xp_SQLCMD的命令来进行渗透处理, 今天因为公司的服务器又中毒了 自己学习了下. 2. 修改SQLSERVER的设置 远程登录数据库 sqlcmd -S 10. ...
- 舵机&数据处理&stm32内存之堆栈溢出(遇到的问题)
产品名称:TOWER PRO(辉盛)大扭力舵机MG996R (MG995升级产品)6v/11Kg厂家编号:MG996R产品净重: 55g产品尺寸: 40.7*19.7*42.9mm产品拉力: 9.4k ...