一、MyBatis和druid简介

  MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。国内最近流行的还有MyBatis-Plus,对Mybatis进行了增强,单表的增删改查可以省略xml文件,本文不作MyBatis-Plus使用介绍。

  Druid首先是一个数据库连接池,但它不仅仅是一个数据库连接池,它还包含一个ProxyDriver,一系列内置的JDBC组件库,一个SQLParser。Druid支持所有JDBC兼容的数据库,包括Oracle、MySql、Derby、Postgresql、SQLServer、H2等等。 

  Druid针对Oracle和MySql做了特别优化,比如Oracle的PSCache内存占用优化,MySql的ping检测优化。Druid在监控、可扩展性、稳定性和性能方面都有明显的优势。Druid提供了Filter-Chain模式的扩展API,可以自己编写Filter拦截JDBC中的任何方法,可以在上面做任何事情,比如说性能监控、SQL审计、用户名密码加密、日志等等。

二、准备数据库

  1. DROP DATBASE IF EXISTS test ;
  2. CREATE DATBASE test CHARACTER SET UTF8 ;
  3. CREATE TABLE user (
  4. uid BIGINT AUTO_INCREMENT ,
  5. `name` VARCHAR(50) not NULL,
  6. age TINYINT not NULL,
  7. PRIMARY KEY(uid)
  8. ) ;
  9. INSERT INTO user(`name`,age) VALUES ('小明',23) ;
  10. INSERT INTO user(`name`,age) VALUES ('小李',25) ;
  11. INSERT INTO user(`name`,age) VALUES ('小伟',26) ;

三、配置druid

1、添加依赖,修改pom.xml

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.0.4</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.1.5</version>
  10. </dependency>

2、配置yml

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource # 配置当前要使用的数据源的操作类型
  4. driver-class-name: org.gjt.mm.mysql.Driver # 配置MySQL的驱动程序类
  5. url: jdbc:mysql://47.52.199.52:3306/test?useUnicode=true&amp;characterEncoding=utf8# 数据库连接地址
    username: test # 数据库用户名
    password: Zhuxing520@ # 数据库连接密码
  1. filer: wall,stat
  2. dbcp2: # 进行数据库连接池的配置
  3. min-idle: # 数据库连接池的最小维持连接数
  4. initial-size: # 初始化提供的连接数
  5. max-total: # 最大的连接数
  6. max-wait-millis: # 等待连接获取的最大超时时间

3、测试类

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @WebAppConfiguration
  4. public class DemoApplicationTests {
  1. @Resource
    private DataSource dataSource;
  1. @Test
    public void testConnection() throws Exception {
    System.out.println(this.dataSource);
    }
  1. }

四、配置Mybatis

1、添加mybatis依赖

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>1.3.0</version>
  5. </dependency>

2、配置yml

  1. mybatis:
  2. config-location: classpath:mapper/mybatis.cfg.xml # mybatis配置文件所在路径
  3. type-aliases-package: com.example.demo.po # 定义所有实体类的别名所在包
  4. mapper-locations: classpath:mapper/*Mapper.xml # 所有的mapper映射文件

3、Mybatis配置文件

mybatis.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!-- 进行Mybatis的相应的环境的属性定义 -->
  7. <settings> <!-- 在本项目之中开启二级缓存 -->
  8. <setting name="cacheEnabled" value="true"/>
  9. </settings>
  10. </configuration>

4、UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.example.demo.dao.UserDao">
  5. <select id="findAll" resultType="UserPO">
  6. SELECT * FROM user;
  7. </select>
  8. </mapper>

5、实体类UserPO.java

  1. package com.example.demo.po;
  2.  
  3. public class UserPO {
  4. private Long uid;
  5. private String name;
  6. private Integer age;
  7.  
  8. public Long getUid() {
  9. return uid;
  10. }
  11.  
  12. public void setUid(Long uid) {
  13. this.uid = uid;
  14. }
  15.  
  16. public String getName() {
  17. return name;
  18. }
  19.  
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23.  
  24. public Integer getAge() {
  25. return age;
  26. }
  27.  
  28. public void setAge(Integer age) {
  29. this.age = age;
  30. }
  31.  
  32. @Override
  33. public String toString() {
  34. return "UserPO{" +
  35. "uid=" + uid +
  36. ", name='" + name + '\'' +
  37. ", age=" + age +
  38. '}';
  39. }
  40. }

6、mapp对应的接口Dao文件

  1. package com.example.demo.dao;
  2.  
  3. import com.example.demo.po.UserPO;
  4. import org.apache.ibatis.annotations.Mapper;
  5.  
  6. import java.util.List;
  7. @Mapper
  8. public interface UserDao {
  9. public List<UserPO> findAll() ;
  10. }

7、测试类

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @WebAppConfiguration
  4. public class DemoApplicationTests {
  5. @Resource
  6. private UserDao userDao;
  7.  
  8. @Test
  9. public void getAllUser(){
  10. System.out.println(userDao.findAll());
  11. }
  12. }

五、mybatis配置sql日志

1、引入依赖

在项目之中去引入 logback 的依赖程序文件:

  1. <dependency>
  2. <groupId>ch.qos.logback</groupId>
  3. <artifactId>logback-core</artifactId>
  4. </dependency>

2、添加配置文件

将 logback.xml 配置文件拷贝到 src/main/resources 目录之中

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2.  
  3. <configuration scan="true">
  4. <property name="APP" value="${project.artifactId}" />
  5. <property name="LOG_HOME" value="/data/www/log/${APP}" />
  6. <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  7. <encoder>
  8. <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
  9. </encoder>
  10. </appender>
  11. <appender name="DETAIL"
  12. class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
  13. <File>${LOG_HOME}/${APP}_detail.log</File>
  14. <encoder>
  15. <pattern>%d{yy-MM-dd.HH:mm:ss.SSS} [%-16t] %-5p %-22c{0} %X{ServiceId} - %m%n</pattern>
  16. </encoder>
  17. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  18. <fileNamePattern>${LOG_HOME}/${APP}_detail.log.%d{yyyyMMdd}</fileNamePattern>
  19. </rollingPolicy>
  20. </appender>
  21. <appender name="ACCESS"
  22. class="ch.qos.logback.core.rolling.RollingFileAppender" additivity="false">
  23. <File>${LOG_HOME}/${APP}_access.log</File>
  24. <encoder>
  25. <pattern>%d{yy-MM-dd.HH:mm:ss.SSS};%X{ServiceId};%m%n</pattern>
  26. </encoder>
  27. <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  28. <fileNamePattern>${LOG_HOME}/${APP}_access.log.%d{yyyyMMdd}</fileNamePattern>
  29. </rollingPolicy>
  30. </appender>
  31.  
  32. <logger name="ACCESS">
  33. <appender-ref ref="ACCESS" />
  34. </logger>
  35.  
  36. <logger name="druid.sql.Statement" level="DEBUG" />
  37. <logger name="com.example.demo.dao" level="TRACE" />
  38.  
  39. <root level="INFO">
  40. <appender-ref ref="DETAIL" />
  41. <appender-ref ref="CONSOLE" />
  42. </root>
  43. </configuration>

添加sql打印:

<logger name="druid.sql.Statement" level="DEBUG" />
<logger name="com.example.demo.dao" level="TRACE" />

六、事务配置及用法

在需要的配置事务的方法上配置@Transactional

  1. @Transactional
  2. public void addUser(){
  3. UserPO userPO1 = new UserPO();
  4. userPO1.setName("王小飞");
  5. userPO1.setAge(24);
  6. userDao.save(userPO1);
  7.  
  8. UserPO userPO2 = new UserPO();
  9. userPO1.setName("王小飞1");
  10. userPO1.setAge(24);
  11. userDao.save(userPO1);
  12. addUser1();
  13. }

七、druid 监控

druid 数据库连接池之所以使用非常广泛,其最主要的原因在于它可以直接提供性能监控。那么本次来针对于当前已经实现好 的 druid 配置来进行性能监控的处理配置。

如果要想进行 Druid 的性能的监控操作,则需要做一些基础配置,例如:你访问的 IP 地址是否是白名单。

1、基础配置类DruidConfig.java

  1. package com.example.demo.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.alibaba.druid.support.http.StatViewServlet;
  4. import com.alibaba.druid.support.http.WebStatFilter;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  7. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10.  
  11. import javax.sql.DataSource;
  12.  
  13. @Configuration
  14. public class DruidConfig {
  15. @Bean
  16. public ServletRegistrationBean druidServlet() { // 主要实现WEB监控的配置处理
  17. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(
  18. new StatViewServlet(), "/druid/*"); // 现在要进行druid监控的配置处理操作
  19. servletRegistrationBean.addInitParameter("allow",
  20. "127.0.0.1,192.168.1.159"); // 白名单
  21. servletRegistrationBean.addInitParameter("deny", "192.168.1.200"); // 黑名单
  22. servletRegistrationBean.addInitParameter("loginUsername", "admin"); // 用户名
  23. servletRegistrationBean.addInitParameter("loginPassword", "123456"); // 密码
  24. servletRegistrationBean.addInitParameter("resetEnable", "false"); // 是否可以重置数据源
  25. return servletRegistrationBean ;
  26. }
  27. @Bean
  28. public FilterRegistrationBean filterRegistrationBean() {
  29. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean() ;
  30. filterRegistrationBean.setFilter(new WebStatFilter());
  31. filterRegistrationBean.addUrlPatterns("/*"); // 所有请求进行监控处理
  32. filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.css,/druid/*");
  33. return filterRegistrationBean ;
  34. }
  35. @Bean
  36. @ConfigurationProperties(prefix = "spring.datasource")
  37. public DataSource druidDataSource() {
  38. return new DruidDataSource();
  39. }
  40. }

2、运行测试

访问http://localhost:8080/druid,使用admin,123456账号密码登陆

springboot系列七:springboot 集成 MyBatis、事物配置及使用、druid 数据源、druid 监控使用的更多相关文章

  1. SpringBoot系列(五)Mybatis整合完整详细版

    SpringBoot系列(五)Mybatis整合 目录 mybatis简介 项目创建 entity dao service serviceImpl mapper controller 1. Mybat ...

  2. 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 ...

  3. 【2.0】SpringBoot2配置Druid数据源及监控

    什么是Druid? Druid首先是Java语言中最好的数据库连接池,也是阿里巴巴的开源项目.Druid是阿里巴巴开发的号称为监控而生的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池, ...

  4. SpringBoot系列七:SpringBoot 整合 MyBatis(配置 druid 数据源、配置 MyBatis、事务控制、druid 监控)

    1.概念:SpringBoot 整合 MyBatis 2.背景 SpringBoot 得到最终效果是一个简化到极致的 WEB 开发,但是只要牵扯到 WEB 开发,就绝对不可能缺少数据层操作,所有的开发 ...

  5. MP实战系列(七)之集成springboot

    springboot是现在比较流行的微服使用的框架,springboot本质上就是将spring+springmvc+mybatis零配置化,基本上springboot的默认配置符合我们的开发.当然有 ...

  6. SpringBoot系列之i18n集成教程

    目录 1.环境搭建 2.resource bundle资源配置 3.LocaleResolver类 4.I18n配置类 5.Thymeleaf集成 SpringBoot系统之i18n国际化语言集成教程 ...

  7. Mybatis-Generator插件的使用与Spring集成Mybatis的配置

    参考:http://blog.51cto.com/zero01/2103687 Mybatis-Generator是一个用于自动生成dao层接口.pojo以及mapper xml的一个Mybatis插 ...

  8. SpringBoot集成Mybatis(0配置注解版)

    Mybatis初期使用比较麻烦,需要各种配置文件.实体类.dao层映射关联.还有一大推其它配置.当然Mybatis也发现了这种弊端,初期开发了generator可以根据表结构自动生成实体类.配置文件和 ...

  9. springBoot系列教程04:mybatis及druid数据源的集成及查询缓存的使用

    首先说下查询缓存:查询缓存就是相同的数据库查询请求在设定的时间间隔内仅查询一次数据库并保存到redis中,后续的请求只要在时间间隔内都直接从redis中获取,不再查询数据库,提高查询效率,降低服务器负 ...

随机推荐

  1. [luogu1962]斐波那契数列

    来提供两个正确的做法: 斐波那契数列双倍项的做法(附加证明) 矩阵快速幂 一.双倍项做法 在偶然之中,在百度中翻到了有关于斐波那契数列的词条(传送门),那么我们可以发现一个这个规律$ \frac{F_ ...

  2. 【转】九大排序算法-C语言实现及详解

    概述 排序有内部排序和外部排序,内部排序是数据记录在内存中进行排序,而外部排序是因排序的数据很大,一次不能容纳全部的排序记录,在排序过程中需要访问外存. 我们这里说说八大排序就是内部排序. 当n较大, ...

  3. python 忽略警告

    import warningswarnings.filterwarnings("ignore")看起来整洁一点...

  4. Ubuntu16.04中禁用UTC解决双系统时间问题

    解决方法一 sudo hwclock -w --localtime 解决方法二 timedatectl set-local-rtc 1 解决方法三 修改/etc/adjtime文件中的UTC,为LOC ...

  5. 忘记ios访问限制密码

    1.使用iTunes将手机备份在本地. 2.下载iBackupBot,打开后在左侧可以看到你的历史备份,选择刚刚备份的文件.依次选择System Files -> HomeDomain -> ...

  6. vue-cli入门(二)——项目结构

    前言 在上一篇项目搭建文章中,我们已经下载安装了node环境以及vue-cli,并且已经成功构建了一个vue-cli项目,那么接下来,我们来梳理一下vue-cli项目的结构. 总体框架 一个vue-c ...

  7. 批处理 ------ @、ECHO OFF、ECHO ON 的使用

    1.在批处理文件中,如果命令前加@,表示这条命令不打印出来,只把结果打印出来,即@是关闭命令本身的回显 2.::在批处理中表示注释某一行 3.ECHO ON表示接下来的命令中(不包括本命令),执行命令 ...

  8. linux command ------ find

    find | grep luoluo 将当前目录及子目录的文件名中含有luoluo的文件过滤出来 | 是管道,把find查找的内容传递给下个命令(grep) find后面不加其他内容(比如路径)表示打 ...

  9. linux command ------ ls

    -rw-r--r-- [d]: content [-]: file [l]: link file [b]: interface device for storage in a device file ...

  10. P1450 [HAOI2008]硬币购物

    题目描述 硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买si的价值的东西.请问每次有多少种付款方法. di,s<=100000 ...