springboot系列七:springboot 集成 MyBatis、事物配置及使用、druid 数据源、druid 监控使用
一、MyBatis和druid简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。国内最近流行的还有MyBatis-Plus,对Mybatis进行了增强,单表的增删改查可以省略xml文件,本文不作MyBatis-Plus使用介绍。
Druid针对Oracle和MySql做了特别优化,比如Oracle的PSCache内存占用优化,MySql的ping检测优化。Druid在监控、可扩展性、稳定性和性能方面都有明显的优势。Druid提供了Filter-Chain模式的扩展API,可以自己编写Filter拦截JDBC中的任何方法,可以在上面做任何事情,比如说性能监控、SQL审计、用户名密码加密、日志等等。
二、准备数据库
- DROP DATBASE IF EXISTS test ;
- CREATE DATBASE test CHARACTER SET UTF8 ;
- CREATE TABLE user (
- uid BIGINT AUTO_INCREMENT ,
- `name` VARCHAR(50) not NULL,
- age TINYINT not NULL,
- PRIMARY KEY(uid)
- ) ;
- INSERT INTO user(`name`,age) VALUES ('小明',23) ;
- INSERT INTO user(`name`,age) VALUES ('小李',25) ;
- INSERT INTO user(`name`,age) VALUES ('小伟',26) ;
三、配置druid
1、添加依赖,修改pom.xml
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.0.4</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.5</version>
- </dependency>
2、配置yml
- spring:
- datasource:
- type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
- driver-class-name: org.gjt.mm.mysql.Driver # 配置MySQL的驱动程序类
- url: jdbc:mysql://47.52.199.52:3306/test?useUnicode=true&characterEncoding=utf8# 数据库连接地址
username: test # 数据库用户名
password: Zhuxing520@ # 数据库连接密码
- filer: wall,stat
- dbcp2: # 进行数据库连接池的配置
- min-idle: # 数据库连接池的最小维持连接数
- initial-size: # 初始化提供的连接数
- max-total: # 最大的连接数
- max-wait-millis: # 等待连接获取的最大超时时间
3、测试类
- @RunWith(SpringRunner.class)
- @SpringBootTest
- @WebAppConfiguration
- public class DemoApplicationTests {
- @Resource
private DataSource dataSource;
- @Test
public void testConnection() throws Exception {
System.out.println(this.dataSource);
}
- }
四、配置Mybatis
1、添加mybatis依赖
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.3.0</version>
- </dependency>
2、配置yml
- mybatis:
- config-location: classpath:mapper/mybatis.cfg.xml # mybatis配置文件所在路径
- type-aliases-package: com.example.demo.po # 定义所有实体类的别名所在包
- mapper-locations: classpath:mapper/*Mapper.xml # 所有的mapper映射文件
3、Mybatis配置文件
mybatis.cfg.xml
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
- <!-- 进行Mybatis的相应的环境的属性定义 -->
- <settings> <!-- 在本项目之中开启二级缓存 -->
- <setting name="cacheEnabled" value="true"/>
- </settings>
- </configuration>
4、UserMapper.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.example.demo.dao.UserDao">
- <select id="findAll" resultType="UserPO">
- SELECT * FROM user;
- </select>
- </mapper>
5、实体类UserPO.java
- package com.example.demo.po;
- public class UserPO {
- private Long uid;
- private String name;
- private Integer age;
- public Long getUid() {
- return uid;
- }
- public void setUid(Long uid) {
- this.uid = uid;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "UserPO{" +
- "uid=" + uid +
- ", name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
6、mapp对应的接口Dao文件
- package com.example.demo.dao;
- import com.example.demo.po.UserPO;
- import org.apache.ibatis.annotations.Mapper;
- import java.util.List;
- @Mapper
- public interface UserDao {
- public List<UserPO> findAll() ;
- }
7、测试类
- @RunWith(SpringRunner.class)
- @SpringBootTest
- @WebAppConfiguration
- public class DemoApplicationTests {
- @Resource
- private UserDao userDao;
- @Test
- public void getAllUser(){
- System.out.println(userDao.findAll());
- }
- }
五、mybatis配置sql日志
1、引入依赖
在项目之中去引入 logback 的依赖程序文件:
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- </dependency>
2、添加配置文件
将 logback.xml 配置文件拷贝到 src/main/resources 目录之中
- <?xml version="1.0" encoding="UTF-8" ?>
- <configuration scan="true">
- <property name="APP" value="${project.artifactId}" />
- <property name="LOG_HOME" value="/data/www/log/${APP}" />
- <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
- <encoder>
- <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
- </encoder>
- </appender>
- <appender name="DETAIL"
- class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
- <File>${LOG_HOME}/${APP}_detail.log</File>
- <encoder>
- <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
- </encoder>
- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}</fileNamePattern>
- </rollingPolicy>
- </appender>
- <appender name="ACCESS"
- class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
- <File>${LOG_HOME}/${APP}_access.log</File>
- <encoder>
- <pattern>%d{yy-MM-dd.HH:mm:ss.SSS};%X{ServiceId};%m%n</pattern>
- </encoder>
- <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
- <fileNamePattern>${LOG_HOME}/${APP}_access.log.%d{yyyyMMdd}</fileNamePattern>
- </rollingPolicy>
- </appender>
- <logger name="ACCESS">
- <appender-ref ref="ACCESS" />
- </logger>
- <logger name="druid.sql.Statement" level="DEBUG" />
- <logger name="com.example.demo.dao" level="TRACE" />
- <root level="INFO">
- <appender-ref ref="DETAIL" />
- <appender-ref ref="CONSOLE" />
- </root>
- </configuration>
添加sql打印:
<logger name="druid.sql.Statement" level="DEBUG" />
<logger name="com.example.demo.dao" level="TRACE" />
六、事务配置及用法
在需要的配置事务的方法上配置@Transactional
- @Transactional
- public void addUser(){
- UserPO userPO1 = new UserPO();
- userPO1.setName("王小飞");
- userPO1.setAge(24);
- userDao.save(userPO1);
- UserPO userPO2 = new UserPO();
- userPO1.setName("王小飞1");
- userPO1.setAge(24);
- userDao.save(userPO1);
- addUser1();
- }
七、druid 监控
druid 数据库连接池之所以使用非常广泛,其最主要的原因在于它可以直接提供性能监控。那么本次来针对于当前已经实现好 的 druid 配置来进行性能监控的处理配置。
如果要想进行 Druid 的性能的监控操作,则需要做一些基础配置,例如:你访问的 IP 地址是否是白名单。
1、基础配置类DruidConfig.java
- package com.example.demo.config;
- import com.alibaba.druid.pool.DruidDataSource;
- import com.alibaba.druid.support.http.StatViewServlet;
- import com.alibaba.druid.support.http.WebStatFilter;
- import org.springframework.boot.context.properties.ConfigurationProperties;
- 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 javax.sql.DataSource;
- @Configuration
- public class DruidConfig {
- @Bean
- public ServletRegistrationBean druidServlet() { // 主要实现WEB监控的配置处理
- ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
- new StatViewServlet(), "/druid/*"); // 现在要进行druid监控的配置处理操作
- servletRegistrationBean.addInitParameter("allow",
- "127.0.0.1,192.168.1.159"); // 白名单
- servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名单
- servletRegistrationBean.addInitParameter("loginUsername", "admin"); // 用户名
- servletRegistrationBean.addInitParameter("loginPassword", "123456"); // 密码
- servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置数据源
- return servletRegistrationBean ;
- }
- @Bean
- public FilterRegistrationBean filterRegistrationBean() {
- FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
- filterRegistrationBean.setFilter(new WebStatFilter());
- filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
- filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
- return filterRegistrationBean ;
- }
- @Bean
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource druidDataSource() {
- return new DruidDataSource();
- }
- }
2、运行测试
访问http://localhost:8080/druid,使用admin,123456账号密码登陆
springboot系列七:springboot 集成 MyBatis、事物配置及使用、druid 数据源、druid 监控使用的更多相关文章
- SpringBoot系列(五)Mybatis整合完整详细版
SpringBoot系列(五)Mybatis整合 目录 mybatis简介 项目创建 entity dao service serviceImpl mapper controller 1. Mybat ...
- spring boot:配置shardingsphere(sharding jdbc)使用druid数据源(druid 1.1.23 / sharding-jdbc 4.1.1 / mybatis / spring boot 2.3.3)
一,为什么要使用druid数据源? 1,druid的优点 Druid是阿里巴巴开发的号称为监控而生的数据库连接池 它的优点包括: 可以监控数据库访问性能 SQL执行日志 SQL防火墙 但spring ...
- 【2.0】SpringBoot2配置Druid数据源及监控
什么是Druid? Druid首先是Java语言中最好的数据库连接池,也是阿里巴巴的开源项目.Druid是阿里巴巴开发的号称为监控而生的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池, ...
- SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)
1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...
- MP实战系列(七)之集成springboot
springboot是现在比较流行的微服使用的框架,springboot本质上就是将spring+springmvc+mybatis零配置化,基本上springboot的默认配置符合我们的开发.当然有 ...
- SpringBoot系列之i18n集成教程
目录 1.环境搭建 2.resource bundle资源配置 3.LocaleResolver类 4.I18n配置类 5.Thymeleaf集成 SpringBoot系统之i18n国际化语言集成教程 ...
- Mybatis-Generator插件的使用与Spring集成Mybatis的配置
参考:http://blog.51cto.com/zero01/2103687 Mybatis-Generator是一个用于自动生成dao层接口.pojo以及mapper xml的一个Mybatis插 ...
- SpringBoot集成Mybatis(0配置注解版)
Mybatis初期使用比较麻烦,需要各种配置文件.实体类.dao层映射关联.还有一大推其它配置.当然Mybatis也发现了这种弊端,初期开发了generator可以根据表结构自动生成实体类.配置文件和 ...
- springBoot系列教程04:mybatis及druid数据源的集成及查询缓存的使用
首先说下查询缓存:查询缓存就是相同的数据库查询请求在设定的时间间隔内仅查询一次数据库并保存到redis中,后续的请求只要在时间间隔内都直接从redis中获取,不再查询数据库,提高查询效率,降低服务器负 ...
随机推荐
- [luogu1962]斐波那契数列
来提供两个正确的做法: 斐波那契数列双倍项的做法(附加证明) 矩阵快速幂 一.双倍项做法 在偶然之中,在百度中翻到了有关于斐波那契数列的词条(传送门),那么我们可以发现一个这个规律$ \frac{F_ ...
- 【转】九大排序算法-C语言实现及详解
概述 排序有内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存. 我们这里说说八大排序就是内部排序. 当n较大, ...
- python 忽略警告
import warningswarnings.filterwarnings("ignore")看起来整洁一点...
- Ubuntu16.04中禁用UTC解决双系统时间问题
解决方法一 sudo hwclock -w --localtime 解决方法二 timedatectl set-local-rtc 1 解决方法三 修改/etc/adjtime文件中的UTC,为LOC ...
- 忘记ios访问限制密码
1.使用iTunes将手机备份在本地. 2.下载iBackupBot,打开后在左侧可以看到你的历史备份,选择刚刚备份的文件.依次选择System Files -> HomeDomain -> ...
- vue-cli入门(二)——项目结构
前言 在上一篇项目搭建文章中,我们已经下载安装了node环境以及vue-cli,并且已经成功构建了一个vue-cli项目,那么接下来,我们来梳理一下vue-cli项目的结构. 总体框架 一个vue-c ...
- 批处理 ------ @、ECHO OFF、ECHO ON 的使用
1.在批处理文件中,如果命令前加@,表示这条命令不打印出来,只把结果打印出来,即@是关闭命令本身的回显 2.::在批处理中表示注释某一行 3.ECHO ON表示接下来的命令中(不包括本命令),执行命令 ...
- linux command ------ find
find | grep luoluo 将当前目录及子目录的文件名中含有luoluo的文件过滤出来 | 是管道,把find查找的内容传递给下个命令(grep) find后面不加其他内容(比如路径)表示打 ...
- linux command ------ ls
-rw-r--r-- [d]: content [-]: file [l]: link file [b]: interface device for storage in a device file ...
- P1450 [HAOI2008]硬币购物
题目描述 硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买si的价值的东西.请问每次有多少种付款方法. di,s<=100000 ...