SpringBoot学习:整合MyBatis,使用Druid连接池
项目下载地址:http://download.csdn.NET/detail/aqsunkai/9805821
(一)添加pom依赖:
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
(二)项目结构如下:
mapper接口在java目录下,相应的写sql语句的xml在resource目录下,在Application启动类中加入注解:
@ServletComponentScan
@MapperScan("com.sun.**.mapper") //配置扫描mapper接口的地址
@ServletComponentScan 设置启动时spring能够扫描到我们自己编写的servlet和filter, 用于Druid监控
@MapperScan 用于扫描的mapper接口
在配置文件中加入:
# mybatis_config
mybatis:
mapper-locations: classpath:mapper/**/*.xml
#datasource
spring:
datasource:
name: era
url: jdbc:mysql://localhost:3306/spring_boot?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username: root
password: 123456
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
#useGlobalDataSourceStat: true
用于扫描mybatis的映射文件xml,和加载连接池
日志文件中加入:
<!--输出sql语句-->
<logger name="com.sun" level="debug" />
用于在控制台打印sql语句
DataSource的配置启动管理类如下:
package com.sun.configuration; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map; @Configuration
@EnableTransactionManagement
/**
* Druid的DataResource配置类
* 凡是被Spring管理的类,实现接口 EnvironmentAware 重写方法 setEnvironment 可以在工程启动时,
* 获取到系统环境变量和application配置文件中的变量。 还有一种方式是采用注解的方式获取 @value("${变量的key值}")
* 获取application配置文件中的变量。 这里采用第一种要方便些
* Created by sun on 2017-1-20.
*/
public class DruidDataSourceConfig implements EnvironmentAware { private RelaxedPropertyResolver propertyResolver; public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
} @Bean
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initialSize")));
datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("minIdle")));
datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("maxWait")));
datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("maxActive")));
datasource.setMinEvictableIdleTimeMillis(
Long.valueOf(propertyResolver.getProperty("minEvictableIdleTimeMillis")));
try {
datasource.setFilters("stat,wall");
} catch (SQLException e) {
e.printStackTrace();
}
return datasource;
} @Bean
public ServletRegistrationBean druidServlet() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<String, String>();
// initParameters.put("loginUsername", "druid");// 用户名
// initParameters.put("loginPassword", "druid");// 密码
initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
initParameters.put("allow", "127.0.0.1"); // IP白名单 (没有配置或者为空,则允许所有访问)
// initParameters.put("deny", "192.168.20.38");// IP黑名单
// (存在共同时,deny优先于allow)
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
} @Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
} // 按照BeanId来拦截配置 用来bean的监控
@Bean(value = "druid-stat-interceptor")
public DruidStatInterceptor DruidStatInterceptor() {
DruidStatInterceptor druidStatInterceptor = new DruidStatInterceptor();
return druidStatInterceptor;
} @Bean
public BeanNameAutoProxyCreator beanNameAutoProxyCreator() {
BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
beanNameAutoProxyCreator.setProxyTargetClass(true);
// 设置要监控的bean的id
//beanNameAutoProxyCreator.setBeanNames("sysRoleMapper","loginController");
beanNameAutoProxyCreator.setInterceptorNames("druid-stat-interceptor");
return beanNameAutoProxyCreator;
} }
后台执行在控制台上输出:
2017-04-07 21:25:15.904 INFO 10500 --- [io-8080-exec-10] c.s.p.controller.UserController : 哈哈哈
2017-04-07 21:25:15.908 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey : ==> Preparing: select id, nickname, email, pswd, create_time, last_login_time, status from sys_user where id = ?
2017-04-07 21:25:15.911 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey : ==> Parameters: 1(Integer)
2017-04-07 21:25:15.918 DEBUG 10500 --- [io-8080-exec-10] c.s.p.m.UserMapper.selectByPrimaryKey : <== Total: 1
2017-04-07 21:25:15.920 INFO 10500 --- [io-8080-exec-10] c.s.p.controller.UserController : admin
在页面上输入http://localhost:8080/boot/druid/可以看到监控到的sql语句执行情况:
SpringBoot学习:整合MyBatis,使用Druid连接池的更多相关文章
- Spring整合JDBC和Druid连接池
我的博客名为黑客之谜,喜欢我的,或者喜欢未来的大神,点一波关注吧!顺便说一下,双十二快到了,祝大家双十二快乐,尽情的买买买~ 如果转载我的文章请标明出处和著名,谢谢配合. 我的博客地址为: https ...
- SpringBoot配置MySql数据库和Druid连接池
1.pom文件增加相关依赖 <dependency> <groupId>mysql</groupId> <artifactId>mysql-connec ...
- SpringMVC+Spring+Mybatis整合,使用druid连接池,声明式事务,maven配置
一直对springmvc和mybatis挺怀念的,最近想自己再搭建下框架,然后写点什么. 暂时没有整合缓存,druid也没有做ip地址的过滤.Spring的AOP简单配置了下,也还没具体弄,不知道能不 ...
- (二)SpringBoot整合常用框架Druid连接池
一,在Pom.xml文件加入依赖 找到<dependencies></dependencies>标签,在标签中添加Druid依赖 <dependency> < ...
- springboot整合druid连接池、mybatis实现多数据源动态切换
demo环境: JDK 1.8 ,Spring boot 1.5.14 一 整合durid 1.添加druid连接池maven依赖 <dependency> <groupId> ...
- MyBatis学习-使用Druid连接池将Maybatis整合到spring
目录 前言 什么是Druid连接池 Druid可以做什么? 导入库包 连接oracle 连接mysql 导入mybatis 导入druid 导入spring-jdbc包 导入spring包 导入spr ...
- spring 5.x 系列第6篇 —— 整合 mybatis + druid 连接池 (代码配置方式)
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...
- spring 5.x 系列第5篇 —— 整合 mybatis + druid 连接池 (xml配置方式)
源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 项目目录结构 1.创建maven工程,除了Spring基本依赖外,还需要导 ...
- 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源
目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...
- 使用MyBatis集成阿里巴巴druid连接池(不使用spring)
在工作中发现mybatis默认的连接池POOLED,运行时间长了会报莫名其妙的连接失败错误.因此采用阿里巴巴的Druid数据源(码云链接 ,中文文档链接). mybatis更多数据源参考博客链接 . ...
随机推荐
- 【JQ】鼠标经过一组button,弹出各自的气泡图片
HTML <div id="bubble1" class="bubble"><img src="../image/p_bubble1 ...
- MFC自定义消息的实现方法
一.概述: 消息机制是windows程序的典型运行机制,在MFC中有很多已经封装好了的消息,如WM_BTN**等.但是在有些特殊情况下我们需要自定义一些消息去完成一些我们所需要的功能,这时候MFC的向 ...
- AutoComplete的使用方法
百度 酷狗,反正使用搜索功能时,都会看到类似于图一这种自动补全的功能,灰常的方便,今天做一个项目,刚好要加这个功能,于是一通百度之后,总算做出来,源代码在文章末尾会提供下载.还有,我这个是参考了网上的 ...
- Classless Interdomain Routing (CIDR)
IP Address Problems IP Address Exhaustion Class A, B, and C address structure inefficient Class B to ...
- NSLog的各种打印格式符 和 打印CGRect时用NSStringFromCGRect
打印CGRect时用NSStringFromCGRect 转载自:http://blog.csdn.net/chenyong05314/article/details/8219270 1. 打印CG开 ...
- Many-to-many relationships in EF Core 2.0 – Part 2: Hiding as IEnumerable
In the previous post we looked at how many-to-many relationships can be mapped using a join entity. ...
- Vue教程:组件Component详解(六)
一.什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功 ...
- Oracle 体系结构三 后台进程
实例后台进程在启动实例时启动,在终止实例时终止运行. SMON SMON(system monitor)起初的任务是安装和打开数据.SMON通过查找和验证数据库控制文件来安装数据库.此后,它通过查找和 ...
- sql中table用法
for c in (select column_value from table(f_split(V_FileID, ','))) loop --若没有填写资格开始结束时间,则填入 select co ...
- android软件开发之TextView控件常用属性
TextView控件 text属性,设置显示的文本 textColor:设置文本颜色 textSize:设置文本字体大小 autoLink:设置文本为电话,URL连接等的时候是否显示为可点击的链接 c ...