一、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审计、用户名密码加密、日志等等。

二、准备数据库

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&amp;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 监控使用的更多相关文章

  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. [luogu1131][bzoj1060][ZJOI2007]时态同步【树形DP】

    传送门:https://www.luogu.org/problemnew/show/P1131 题目大意 给你一棵树,每条边有边权,要求增加一些边的边权,使得根节点到每个叶子节点的距离相等,求出最少共 ...

  2. Python中threading的join和setDaemon的区别及用法

    Python多线程编程时经常会用到join()和setDaemon()方法,基本用法如下: join([time]): 等待至线程中止.这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或 ...

  3. luogu4185 [USACO18JAN]MooTube (并查集)

    类似于NOI2018d1t1的离线做法,把询问存下来,排个序,然后倒着给并查集加边,每次询问并查集联通块大小 #include<bits/stdc++.h> #define ll long ...

  4. bzoj5281/luogu4377 Talent Show (01分数规划+背包dp)

    就是01分数规划的思路,只不过当把w[i]-r*t[i]>0的选完以后如果w值还没达到要求,那就再01背包dp一下就好了(dp时w值>W的时候就存在W里就不会爆内存了). (跑得很慢..大 ...

  5. A1005. Spell It Right

    Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output e ...

  6. MyEclipse 检出新项目后,如果项目名称签名有个红色感叹号

    MyEclipse 检出新项目后,如果项目名称签名有个红色感叹号,那么看 Problems中的错误提示(如果找不到Problems窗口,点 菜单栏的 Window——Reset Perspective ...

  7. SQL Server 操作XML数据

    .xml.exist 输入为XQuery表达式,返回0,1或是Null.0表示不存在,1表示存在,Null表示输入为空 .xml.value 输入为XQuery表达式,返回一个SQL Server标量 ...

  8. Tensorflow-gpu版本安装

    目录 服务器选型 NVIDIA GPU驱动安装 cuda和cudnn的安装 cuda安装 cudnn的安装 tensorflow-gpu安装 最近给公司部署一套深度学习相关的环境,以tensorflo ...

  9. 关于TCP连接状态的解释

    TCP各个状态主要存在于三次握手和四次挥手的过程 1.TCP建立连接时的三次握手: 服务端应用监听端口处于LISTEN状态,等待建立连接. 第一次握手:客户端发送SYN=一个随机数,然后进入SYN_S ...

  10. mysql常用sql汇总

    给一张表新增一个字段 ALTER table student add zz INT() DEFAULT COMMENT '0是授权 1未授权' 给表student 新增一个zz的字段 默认是0 后面是 ...