MyBatis默认提供了一个数据库连接池PooledDataSource,在此我们使用阿里提供的Druid数据库连接池

项目下载:https://files.cnblogs.com/files/applesnt/springboot-db.zip

1:建表sql语句

CREATE TABLE `bank_card` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) DEFAULT NULL,
`money` int(11) DEFAULT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; INSERT INTO `bank_card` VALUES ('1', '张三', '1000');
INSERT INTO `bank_card` VALUES ('2', '李红', '1000');

2:pom引入相关依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.22</version>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

3:构建mybatis配置文件

resources\mybatis\config\mybatis-config.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> <settings>
<setting name="logImpl" value="STDOUT_LOGGING" /> <!--打印sql语句-->
<setting name="lazyLoadingEnabled" value="true"/> <!-- 全局性设置懒加载 -->
<setting name="aggressiveLazyLoading" value="false"/> <!-- 每个属性都按需加载 -->
<setting name="mapUnderscoreToCamelCase" value="true" /><!-- 开启驼峰命名 -->
</settings> </configuration>

4:构建javaBean

com\applesnt\springbootdb\vo\AccountVo.java

package com.applesnt.springbootdb.vo;

import lombok.Data;

@Data
public class AccountVo {
/*编号*/
private Integer userId;
/*用户*/
private String userName;
/*存款*/
private Integer money;
}

5:构建mapper接口

package com.applesnt.springbootdb.mapper;

import com.applesnt.springbootdb.vo.AccountVo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List; //mapper接口要使用@Mapper注解 如果不加 可以再启动类上加上@MapperScan注解
@Mapper
//防止自动注入的时候出红线
@Component
public interface BankAccountMapper { /*添加银行账户*/
public void addBankAccount(AccountVo accountVo);
/*查询所有银行账户*/
public List<AccountVo> getAllBankAccount();
/*查询指定的银行账户*/
public AccountVo getByIdBankAccount(Integer id);
/*删除指定的银行账户*/
public void deleteBankAccount(Integer id);
/*银行账户转入*/
public void updateInBankAccount(AccountVo accountVo);
/*银行账户转出*/
public void updateOutBankAccount(AccountVo accountVo);
}

6:构建mapper配置文件

resources\mybatis\mapper\BankAccountMapper.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接口的全路径-->
<mapper namespace="com.applesnt.springbootdb.mapper.BankAccountMapper"> <!--
useGeneratedKeys:开启获取自增长主键
keyProperty:把获取的自增长主键的值给哪个属性
parameterType="AccountVo":别名
-->
<!--添加-->
<insert id="addBankAccount" useGeneratedKeys="true" keyProperty="userId" parameterType="AccountVo">
insert into bank_card(user_name, money) values (#{userName},#{money})
</insert>
<!--查询所有-->
<select id="getAllBankAccount" resultType="AccountVo">
select * from bank_card
</select>
<!--查询指定-->
<select id="getByIdBankAccount" resultType="AccountVo" parameterType="int">
select * from bank_card where user_id = #{userId}
</select>
<!--删除指定-->
<delete id="deleteBankAccount" parameterType="int">
delete from bank_card where user_id = #{userId}
</delete>
<!--修改-->
<update id="updateInBankAccount" parameterType="AccountVo">
update bank_card
<set>
money = money+#{money}
</set>
where user_id = #{userId}
</update>
<!--修改-->
<update id="updateOutBankAccount" parameterType="AccountVo">
update bank_card
<set>
money = money-#{money}
</set>
where user_id = #{userId}
</update> </mapper>

7:application.yml相关配置

server:
port: 80 #访问端口 spring:
datasource:
username: root #数据库的用户名
password: 123456 #数据库的用户密码
url: jdbc:mysql://127.0.0.1:3306/my_test?useUnicode=true&characterEncoding=utf8 # 数据库连接地址
driver-class-name: com.mysql.cj.jdbc.Driver # 数据库驱动
type: com.alibaba.druid.pool.DruidDataSource # 数据库类型 使用druid
druid:
initial-size: 5 #初始化时建立物理连接的个数(缺省值:0)
max-active: 200 # 最大连接池数量(缺省值:8)
min-idle: 1 # 最小链接池数量
max-wait: 6000 #获取连接时最大等待时间,单位毫秒
time-between-eviction-runs-millis: 6000
min-evictable-idle-time-millis: 30000 # 配置一个连接在池中最小生存的时间,单位是毫秒
validation-query: select 'x' from dual #用来检测连接是否有效的sql,要求是一个查询语
pool-prepared-statements: false #是否缓存preparedStatement mysql 建议关闭
test-on-borrow: false #申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
test-on-return: false # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
test-while-idle: true # 建议配置为true,不影响性能,并且保证安全性
connection-init-sqls: select 1 from dual # 物理连接初始化的时候执行的sql
#监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
filters: stat,wall,log4j2
filter:
stat: # 监控统计
db-type: mysql
log-slow-sql: true
slow-sql-millis: 2000
wall: #防御sql
enabled: true
db-type: mysql
config:
delete-allow: true #运行执行删除语句
drop-table-allow: false #不运行执行删除表语句
log4j2:
enabled: true
stat-view-servlet: #statViewServlet配置
enabled: true #开启状态
url-pattern: "/druid/*" #监控页面访问路径
reset-enable: false # 禁止手动重置监控数据
login-username: admin # 用户名
login-password: admin # 密码
web-stat-filter: #WebStatFilter配置
enabled: true #开启状态
url-pattern: "/*" #拦截请求
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*" #排除请求
session-stat-max-count: 1000 # 监控最大session数,默认是1000
session-stat-enable: true # 是否启用session的统计功能
profile-enable: true # 是否启用监控单个Url调用的sql列表
principal-session-name: session_user_key #使druid当前session的用户是谁
principal-cookie-name: cookie_user_key #使druid当前user的用户是谁
mybatis:
config-location: classpath:mybatis/config/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
type-aliases-package: com.applesnt.springbootdb.vo

8:构建service接口

com\applesnt\springbootdb\service\BankAccountService.java

package com.applesnt.springbootdb.service;

import com.applesnt.springbootdb.vo.AccountVo;
import java.util.List; public interface BankAccountService { /*添加银行账户*/
public void addBankAccount(AccountVo accountVo);
/*查询所有银行账户*/
public List<AccountVo> getAllBankAccount();
/*查询指定的银行账户*/
public AccountVo getByIdBankAccount(Integer id);
/*删除指定的银行账户*/
public void deleteBankAccount(Integer id);
/*银行账户转账*/
public void zzBankAccount(AccountVo inAccountVo,AccountVo outAccountVo); }

9:构建service接口实现类

com\applesnt\springbootdb\service\impl\BankAccountServiceImpl.java

package com.applesnt.springbootdb.service.impl;

import com.applesnt.springbootdb.mapper.BankAccountMapper;
import com.applesnt.springbootdb.service.BankAccountService;
import com.applesnt.springbootdb.vo.AccountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; @Service
public class BankAccountServiceImpl implements BankAccountService { @Autowired
private BankAccountMapper bankAccountMapper; /*添加银行账户*/
@Override
public void addBankAccount(AccountVo accountVo) {
this.bankAccountMapper.addBankAccount(accountVo);
}
/*查询所有银行账户*/
@Override
public List<AccountVo> getAllBankAccount() {
return bankAccountMapper.getAllBankAccount();
}
/*查询指定的银行账户*/
@Override
public AccountVo getByIdBankAccount(Integer id) {
return bankAccountMapper.getByIdBankAccount(id);
}
/*删除指定的银行账户*/
@Override
public void deleteBankAccount(Integer id) {
bankAccountMapper.deleteBankAccount(id);
} /*银行账户转账*/
@Override
@Transactional //事务管理注解 同时还要在启动类中开启
public void zzBankAccount(AccountVo inAccountVo, AccountVo outAccountVo) { bankAccountMapper.updateInBankAccount(inAccountVo);
//模拟转账出错 开启事务
if(1==1){
throw new RuntimeException("转账失败");
}
bankAccountMapper.updateOutBankAccount(outAccountVo);
}
}

10:构建controller请求

com\applesnt\springbootdb\controller\BankAccountController.java

package com.applesnt.springbootdb.controller;

import com.applesnt.springbootdb.service.BankAccountService;
import com.applesnt.springbootdb.vo.AccountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; @RestController
public class BankAccountController { @Autowired
private BankAccountService bankAccountService; /*添加银行账户*/
@RequestMapping("/add")
public String addBankAccount() {
AccountVo accountVo = new AccountVo();
accountVo.setUserName("赵晗");
accountVo.setMoney(1000);
bankAccountService.addBankAccount(accountVo);
return "success";
}
/*查询所有银行账户*/
@RequestMapping("/all")
public String getAllBankAccount(){
List<AccountVo> list = bankAccountService.getAllBankAccount();
for (AccountVo accountVo : list) {
System.out.println(accountVo.toString());
}
return "success";
}
/*查询指定的银行账户*/
@RequestMapping("/get")
public String getByIdBankAccount(){
AccountVo byIdBankAccount = bankAccountService.getByIdBankAccount(6);
System.out.println(byIdBankAccount.toString());
return "success";
}
/*删除指定的银行账户*/
@RequestMapping("/delete")
public String deleteBankAccount(){
bankAccountService.deleteBankAccount(6);
return "success";
}
/*银行账户转账*/
@RequestMapping("/zz")
public String zzBankAccount(){
//转入账户
AccountVo inAccountVo = new AccountVo();
inAccountVo.setUserId(1);
inAccountVo.setMoney(200);
//转出账户
AccountVo outAccountVo = new AccountVo();
outAccountVo.setUserId(2);
outAccountVo.setMoney(200); bankAccountService.zzBankAccount(inAccountVo,outAccountVo);
return "success";
}
}

11:主配置文件

package com.applesnt.springbootdb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication
//开启事务管理
@EnableTransactionManagement
//@MapperScan({"com.applesnt.springboot.mapper","com.kfit.user"}) 多路径
//@MapperScan("com.applesnt.springboot.mapper")
public class SpringbootDbApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootDbApplication.class, args);
}
}

12:Druid监控页面访问

可以在druid监控页面看到所有的request请求和SQL语句

Springboot:整合Mybaits和Druid【监控】(十一)的更多相关文章

  1. Springboot整合shardingsphere和druid进行读写分离

    最近在使用springboot整合shardingsphere和druid实现mysql数据库读写分离时遇到了一些问题,特此记录一下. 依赖版本 Springboot 2.1.6.RElEASE sh ...

  2. springboot整合mybaits注解开发

    springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...

  3. 9 — springboot整合jdbc、druid、druid实现日志监控 — 更新完毕

    1.整合jdbc.druid 1).导入依赖 <dependency> <groupId>org.springframework.boot</groupId> &l ...

  4. (二)SpringBoot整合常用框架Druid连接池

    一,在Pom.xml文件加入依赖 找到<dependencies></dependencies>标签,在标签中添加Druid依赖 <dependency> < ...

  5. SpringBoot整合Actuator进行健康监控

    一.Actuator介绍 SpringBoot自带监控功能Actuator,通过 restful api 请求来监管.审计.收集应用的运行情况,可以帮助实现对程序内部运行情况监控,比如监控状况.Bea ...

  6. springboot~集成DataSource 与 Druid监控配置

    介绍 Druid首先是一个数据库连接池.Druid是目前最好的数据库连接池,在功能.性能.扩展性方面,都超过其他数据库连接池,Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部 ...

  7. springBoot 整合mybaits 逆向工程

    pom.xml文件中增加配置项 <build> <plugins> <plugin> <groupId>org.springframework.boot ...

  8. spring-boot整合mybaits多数据源动态切换案例

    1.运行环境 开发工具:intellij idea JDK版本:1.8 项目管理工具:Maven 4.0.0 2.GITHUB地址 https://github.com/nbfujx/springBo ...

  9. SpringBoot整合SpringAdmin搭建监控平台

    在SpringBoot整合Actuator进行健康监控中,胜金讲述了通过Actuator进行健康监控,但是学习API并根据API开发前端需要花费相当大的精力,本次胜金就写一下通过SpringAdmin ...

随机推荐

  1. 微信内置浏览器对于html5的支持

    微信内置浏览器对于html5的支持 来源: 作者: 热度:102 日期:14-06-10, 09:10 AM 我在做针对微信的HTML5应用, 目前遇到的几个问题是 一. 安卓版微信直接调用系统浏览器 ...

  2. python之目录

    一.python基础 ​ python之字符串str操作方法 ​ python之int (整型) ​ python之bool (布尔值) ​ python之str (字符型) ​ python之ran ...

  3. python之序列化、OS、SYS、hashlib模块

    一.序列化模块 1.序列化模块的用途 将一种数据结构转换成特殊的序列(特殊字符串,bytes),并且还可以转换回去 凡是数据通过网络传出去最终的格式必须bytes 2.json模块 json 是一种轻 ...

  4. Arcgis连接SQL Server提示试图使用不支持的旧版SQL Server客户端通信软件进行连接

    一般提示这种错误的是arcgis服务区和SQL server服务器不在同一台电脑上,但在同一个局域网. 遇到这种问题是arcgis 服务器客户端连接SQL server数据库有问题,要么是客户端没有安 ...

  5. Linux下的ngnix安装与启动

     Linux安装Nginx 1.安装gcc gcc-c++(如新环境,未安装请先安装)$ yum install -y gcc gcc-c++2.安装wget$ yum -y install wget ...

  6. Python python 数据类型的相互转换

    # number 之间的相互转换 # int <=> float var1 = 1; print(type(var1)) #<class 'int'> res1 = float ...

  7. [React]核心概念

    本文是对React文档:核心概念部分的笔记,内容大致与文档相同. 文档链接 React哲学部分写的很好,务必要看 JSX JSX是JS的语法扩展,配合react使用,为JS和HTML的混写 JSX支持 ...

  8. Python第十二章-多进程和多线程01-多进程

    多进程和多线程 一.进程 1.1 进程的引入 现实生活中,有很多的场景中的事情是同时进行的,比如开车的时候 手和脚共同来驾驶汽车,再比如唱歌跳舞也是同时进行的:试想,如果把唱歌和跳舞这2件事情分开依次 ...

  9. scikit_learn分类器详解

    1       分类 分类是将事物按特性进行分类,例如将手写数字图片分类为对应的数字. 1.1  MINIST数字图片集分类 MINST就是一个70000张规格较小的手写数字图片,如何将他们分类为对应 ...

  10. Java实现tif/tiff/bmp图片转换png图片

    package org.analysisitem20181016.test; import java.io.File; import java.io.FileOutputStream; import ...