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. IP协议的助手 —— ICMP 协议

    IP协议的助手 —— ICMP 协议 IP协议的助手 —— ICMP 协议 ping 是基于 ICMP 协议工作的,所以要明白 ping 的工作,首先我们先来熟悉 ICMP 协议. ICMP 是什么? ...

  2. 用python的BeautifulSoup分析html

    序言 之前用python爬取网页的时候,一直用的是regex或者自带的库sgmllib里的SGMLParser.但是遇到复杂一点的情况时,SGMLParser往往就不那么给力了!(哈,难道说我 too ...

  3. coding++:java—提取Html文本字符串中的内容

    package com.tree.ztree_demo; import java.util.regex.Matcher; import java.util.regex.Pattern; public ...

  4. JVM中内存分配策略及堆和栈的比较

    最近愈发对JVM底层的运行 原理产生了兴趣,遂查阅相关资料以备忘. 内存分配策略 根据编译原理的观点,程序运行时的内存分配,有三种策略,分别为静态的.堆式的.栈式的. 静态存储分配指的是在编译时就能确 ...

  5. windows server 2016 远程桌面mstsc DPI(更改文本、应用和其他项目大小) 设置

    windows server 2016 远程桌面mstsc DPI 设置 在高分辨率机器2K,4K,8K,登入使用window远程桌面mstsc时,登入后虽然分辨率变成了和cilent一样分辨率 但是 ...

  6. [vijos1144]小胖守皇宫<树形dp>

    题目链接:https://vijos.org/p/1144 woc我竟然A了,这道经典的树形dp或者说是树形dp的入门题我终于过了,虽然之前做过一些树形dp的题,但是这题开始还是一脸懵逼,dp方程如何 ...

  7. 牛客寒假基础集训营 | Day1 E-rin和快速迭代(暴力 + 优化)

    E-rin和快速迭代 题目描述 rin最近喜欢上了数论. 然而数论实在太复杂了,她只能研究一些简单的问题. 这天,她在研究正整数因子个数的时候,想到了一个"快速迭代"算法.设 f( ...

  8. flask-sqlalchemy的基本使用

    flask-sqlalchemy 1 .配置应用和基本使用 和sqlalchemy一样,先定义好数据库配置和db_url.然后在app的config加入SQLALCHEMY_DATABASE_URI等 ...

  9. 细数Java项目中用过的配置文件(YAML篇)

    灵魂拷问:YAML,在项目中用过没?它与 properties 文件啥区别? 目前 SpringBoot.SpringCloud.Docker 等各大项目.各大组件,在使用过程中几乎都能看到 YAML ...

  10. Linux管理,例行性工作,at和cron

    at 仅执行一次就结束调度(服务atd必须启动) at的配置信息 1.我们设定的at进程其实都是被以文本的方式写入到/var/spool/at/目录内,然后这些设定的进程便会等待atd服务来启动这些进 ...