文章目录

  • SpringBoot整合数据库
    • 前言:关于本节的问题汇总
    • 1、整合JDBC
      • 1.1、SpringData简介
      • 1.2、整合JDBC
      • 1.3、分析源码
      • 1.4、JdbcTemplate
      • 1.5、增删改查案例
    • 2、整合Druid
      • 2.1、Druid简介
      • 2.2、配置数据源
      • 2.3、配置 Druid 数据源监控
      • 2.4、配置 Druid web监控过滤器
    • 3、整合 Mybatis 框架
      • 3.1、导入依赖
      • 3.2、配置数据库连接信息
      • 3.3、编写实体类
      • 3.4、编写mapper接口
      • 3.5、编写mapper映射文件
      • 3.6、核心配置文件指定mapper映射文件
      • 3.7、解决 maven 资源过滤问题
      • 3.8、编写Controller测试

SpringBoot整合数据库

前言:关于本节的问题汇总

遇到问题可参考下面文章内容
https://blog.csdn.net/qq_58233406/article/details/126914605

1、整合JDBC

1.1、SpringData简介

  • 对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
  • Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
  • Sping Data 官网:https://spring.io/projects/spring-data
  • 数据库相关的启动器 :弹簧启动参考文档 (spring.io)(2.7.3)

1.2、整合JDBC

  • 导入测试数据库
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT
CHARACTER SET utf8 */;USE `springboot`;/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;CREATE TABLE `department` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部门id',
`department_name` varchar(20) NOT NULL COMMENT '部门名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8;
/*Data for the table `department` */insert into `department`(`id`,`department_name`) values (101,'技术部'),
(102,'销售部'),(103,'售后部'),(104,'后勤部'),(105,'运营部');/*Table structure for table `employee` */
DROP TABLE IF EXISTS `employee`;CREATE TABLE `employee` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇员id',
`last_name` varchar(100) NOT NULL COMMENT '名字',
`email` varchar(100) NOT NULL COMMENT '邮箱',
`gender` int(2) NOT NULL COMMENT '性别1 男, 0 女',
`department` int(3) NOT NULL COMMENT '部门id',
`birth` datetime NOT NULL COMMENT '生日',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;
/*Data for the table `employee` */insert into
`employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) values
(1001,'张三','243357594@qq.com',1,101,'2021-03-06 15:04:33'),(1002,'李
四','243357594@qq.com',1,102,'2021-03-06 15:04:36'),(1003,'王
五','243357594@qq.com',0,103,'2021-03-06 15:04:37'),(1004,'赵
六','243357594@qq.com',1,104,'2021-03-06 15:04:39'),(1005,'孙
七','243357594@qq.com',0,105,'2021-03-06 15:04:45');
  • 新建一个项目测试:SpringBoot-06-data

  • 项目建好之后,发现自动帮我们导入了如下的启动器:
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
  • 编写yaml配置文件连接数据库(本人Mysql版本为5.1.47)
spring:datasource:username: rootpassword: 1234url: jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8driver-class-name: com.mysql.jdbc.Driver

补充:Mysql8.0版本为如下配置

spring: datasource:username: rootpassword: 1234# ?serverTimezone=UTC解决时区的报错url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Driver
  • 测试
package com.example.springboot06data;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;@SpringBootTest
class SpringBoot06DataApplicationTests {@AutowiredDataSource dataSource;@Testvoid contextLoads() throws SQLException {// 查看默认数据源System.out.println(dataSource.getClass());// 获得连接Connection connection = dataSource.getConnection();System.out.println(connection);// 关闭连接connection.close();}}

可以看到:默认数据源为 class com.zaxxer.hikari.HikariDataSource

补充:如果datasource报错,就降低springboot版本,我原本使用的2.7.3虽然报红线但是还可以使用,不想报红线可以降低版本为2.6.11

1.3、分析源码

全局搜索:DataSourceAutoConfiguration文件

@Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})
protected static class PooledDataSourceConfiguration {protected PooledDataSourceConfiguration() {}
}
  • 这里导入的类都在 DataSourceConfiguration 配置类下,可以看出 Spring Boot 2.6.3默认使用 HikariDataSource 数据源,而以前版本,如 Spring Boot 1.5默认使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源;
  • HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat jdbc 等连接池更加优秀;
  • 可以使用 spring.datasource.type 指定自定义的数据源类型,值为要使用的连接池实现的完全限定名
  • 关于数据源不做过多介绍,有了数据库连接,显然就可以CRUD操作数据库了。但是仍需要先了解一个对象——JdbcTemplate

1.4、JdbcTemplate

  1. 有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接 (java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;
  2. 即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate
  3. 数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
  4. Spring Boot不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用。
  5. JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的JdbcTemplateConfiguration类。

JdbcTemplate主要提供以下几类方法

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate 方法用于执行批处理相关语句;
  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

1.5、增删改查案例

  • 查询
/***     查询employee表中所有数据*     List 中的1个 Map 对应数据库的 1行数据*     Map 中的 key 对应数据库的字段名,value 对应数据库的字段值*/
@GetMapping("/list")
public  List<Map<String,Object>> userList() {String sql = "select * from employee";List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);return maps;
}

  • 增加员工
/***  增加员工*/
@GetMapping("/add")
public int add(){//new Date().toLocaleString默认设置为12小时,会显示上午、下午.可设置为24小时var time=new Date().toLocaleString('chinese',{hour12:false});String sql = "insert into employee(`last_Name`,`email`,`gender`,`department`,`birth`) values('BoBooY','123456789@qq.com',1,105,'" + new Date().toLocaleString()+"')";int updateRows = jdbcTemplate.update(sql);return updateRows;
}
  • 修改员工
/***  修改员工*/
@GetMapping("/update/{id}")
public int update(@PathVariable("id") int id) {String sql = "update employee set last_Name=?,email=? where id=" + id;Object[] data = new Object[2];data[0] = "BoBooY";data[1] = "123456789@qq.com";int updateRows = jdbcTemplate.update(sql,data);return updateRows;
}
  • 删除员工
/***  删除员工*/
@GetMapping("/delete/{id}")
public int delete(@PathVariable("id") int id) {String sql = "delete from employee where id="+ id;int updateRows = jdbcTemplate.update(sql);return updateRows;
}
  • 完整代码(JdbcController
package com.example.springboot06data.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import java.util.Date;
import java.util.List;
import java.util.Map;/*** @author BoBooY* @date 2022/9/14 21:44*/
@RestController
public class JdbcController {/***  Spring Boot 默认提供了数据源,默认提供了 org.springframework.jdbc.core.JdbcTemplate*  JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作*  还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接*/@AutowiredJdbcTemplate jdbcTemplate;/***     查询employee表中所有数据*     List 中的1个 Map 对应数据库的 1行数据*     Map 中的 key 对应数据库的字段名,value 对应数据库的字段值*/@GetMapping("/list")public  List<Map<String,Object>> userList() {String sql = "select * from employee";List<Map<String,Object>> maps = jdbcTemplate.queryForList(sql);return maps;}/***  增加员工*/@GetMapping("/add")public int add(){//new Date().toLocaleString默认设置为12小时,会显示上午、下午.可设置为24小时var time=new Date().toLocaleString('chinese',{hour12:false});String sql = "insert into employee(`last_Name`,`email`,`gender`,`department`,`birth`) values('BoBooY','123456789@qq.com',1,105,'" + new Date().toLocaleString()+"')";int updateRows = jdbcTemplate.update(sql);return updateRows;}/***  修改员工*/@GetMapping("/update/{id}")public int update(@PathVariable("id") int id) {String sql = "update employee set last_Name=?,email=? where id=" + id;Object[] data = new Object[2];data[0] = "BoBooY";data[1] = "123456789@qq.com";int updateRows = jdbcTemplate.update(sql,data);return updateRows;}/***  删除员工*/@GetMapping("/delete/{id}")public int delete(@PathVariable("id") int id) {String sql = "delete from employee where id="+ id;int updateRows = jdbcTemplate.update(sql);return updateRows;}
}

2、整合Druid

2.1、Druid简介

  • Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
  • Druid是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等DB池的优点,同时加入了日志监控。
  • Druid可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的DB连接池。
  • Spring Boot 2.0 以上默认使用Hikari数据源,可以说Hikari与Driud都是当前Java Web上最优秀的数据源,我们来重点介绍Spring Boot如何集成Druid数据源,如何实现数据库监控。
  • Github地址:https://github.com/alibaba/druid

com.alibaba.druid.pool.DruidDataSource 基本配置参数如下:

配置 缺省值 说明
name 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。如果没有配置,将会生成一个名字,格式是:“DataSource-” + System.identityHashCode(this).
url 连接数据库的url,不同数据库不一样。例如: mysql: jdbc:mysql://10.20.153.104:3306/druid2 oracle: jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username 连接数据库的用户名
password 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。
driverClassName 根据url自动识别 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName
initalSize 0 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
maxActive 8 最大连接池数量
maxIdle 8 已经不再使用,配置了也没效果
minIdle 最小连接池数量
maxWait 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。
poolPreparedStatements false 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
maxOpenPreparedStatements -1 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100
validationQuery 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。
validationQueryTimeout 单位:秒,检测连接是否有效的超时时间。底层调用jdbc Statement对象的void setQueryTimeout(int seconds)方法。
testOnBorrow true 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
testOnReturn false 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testWhileIdle false 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
timeBetweenEvictionRunsMillis 1分钟 (1.0.14) 有两个含义: 1) Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明。
numTestsPerEvictionRun 不再使用,一个DruidDataSource只支持一个EvictionRun
numTestsPerEvictionRun 30分钟 (1.0.14) 连接保持空闲而不被驱逐的最长时间
connectionInitSqls 物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters 属性类型是字符串,通过别名的方式配置扩展插件,常用 的插件有:监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall
proxyFilters 类型是List,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系

2.2、配置数据源

  • 添加上Druid数据源依赖。
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version>
</dependency>
  • 切换数据源,之前已经说过 Spring Boot 2.0 以上默认使用com.zaxxer.hikari.HikariDataSource数据源,但可以通过spring.datasource.type指定数据源。
spring:datasource:username: rootpassword: root# ?serverTimezone=UTC解决时区的报错url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
  • 数据源切换之后,在测试类中注入DataSource,然后获取到它,输出一看便知是否成功切换;

  • 设置数据源连接初始化大小、最大连接数、等待时间、最小连接数 等设置项,可以查看源码。
spring:datasource:username: rootpassword: 1234url: jdbc:mysql://localhost:3306/springboot?useSSL=true&useUnicode=true&characterEncoding=utf8driver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource # 自定义数据源#数据源#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  • 导入Log4j的依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version>
</dependency>
  • 为DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用Spring Boot的自动生成了;需要自己添加DruidDataSource组件到容器中,并绑定属性;
  • 编写DruidConfig
import java.util.HashMap;
import java.util.Map;/*** @author BoBooY* @date 2022/9/17 17:19*/
@Configuration
public class DruidConfig {/*** 将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建* 绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效** @ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中* 前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中*/@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druidDataSource() {return new DruidDataSource();}
}

2.3、配置 Druid 数据源监控

  • Druid 数据源具有监控的功能,并提供了一个web界面方便用户查看,类似安装路由器时,人家也提 供了一个默认的web页面。
  • 所以第一步需要设置 Druid 的后台管理页面,比如登录账号、密码等;配置后台管理;
  • 编写DruidConfig
@Bean
public ServletRegistrationBean statViewServlet() {ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到Map<String, String> initParams = new HashMap<>();initParams.put("loginUsername", "admin");initParams.put("loginPassword", "123456");// deny:Druid 后台拒绝谁访问// initParams.put("deny", "192.168.1.20");表示禁止此ip访问bean.setInitParameters(initParams);return bean;
}
  • 访问 http://localhost:8080/druid

2.4、配置 Druid web监控过滤器

  • 编写DruidConfig
// 配置 Druid 监控 之  web 监控的 filter
// WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());// exclusions:设置哪些请求进行过滤排除掉,从而不进行统计HashMap<String, String> initParams = new HashMap<>();initParams.put("exclusions","*.js,*.css,/druid/*,/jdbc/*");bean.setInitParameters(initParams);// "/*" 表示过滤所有请求bean.setUrlPatterns(Arrays.asList("/*"));return bean;
}

3、整合 Mybatis 框架

  • 官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
  • Maven仓库地址:Maven Repository: org.mybatis.spring.boot » mybatis-spring-boot-starter » 2.2.1 (mvnrepository.com)
  • GitHub官网:https://github.com/mybatis/spring-boot-starter

3.1、导入依赖

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version>
</dependency>

3.2、配置数据库连接信息

  • application.yaml
spring:datasource:username: rootpassword: 1234url: jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=utf8driver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource # 自定义数据源#数据源#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

3.3、编写实体类

  • User 类
package com.springboot07mybatis.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** @author BoBooY* @date 2022/9/17 21:07*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {private int id;private String name;private String pwd;
}

3.4、编写mapper接口

  • UserMapper
package com.springboot07mybatis.mapper;import com.springboot07mybatis.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;import java.util.List;/*** @author BoBooY* @date 2022/9/17 21:08*/
@Repository
@Mapper
public interface UserMapper {List<User> getUserList();User getUserById(int id);int addUser(User user);int updateUser(User user);int deleteUser(int id);
}

3.5、编写mapper映射文件

  • UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springboot07mybatis.mapper.UserMapper"><!--开启缓存<cache/>--><select id="getUserList" resultType="User">select * from user</select><select id="getUserById" resultType="User" parameterType="int">select * from user where id = #{id}</select><insert id="addUser" parameterType="User">insert into user(`name`,`pwd`) values(#{name},#{pwd})</insert><update id="updateUser" parameterType="User">update user set `name`=#{name},`pwd`=#{pwd} where `id`=#{id}</update><delete id="deleteUser" parameterType="int">delete from user where `id`=#{id}</delete>
</mapper>

3.6、核心配置文件指定mapper映射文件

  • application.yaml
#配置Mybatis
mybatis:# 指定myBatis的核心配置文件与Mapper映射文件mapper-locations: classpath:mybatis/mapper/*.xml# 注意:对应实体类的路径type-aliases-package: com.springboot07mybatis.pojo

3.7、解决 maven 资源过滤问题

  • pom.xml
<build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include><include>**/*.yml</include><include>**/*.yaml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include><include>**/*.yml</include><include>**/*.yaml</include></includes><filtering>false</filtering></resource></resources>
</build>

3.8、编写Controller测试

  • UserController
package com.springboot07mybatis.controller;import com.springboot07mybatis.mapper.UserMapper;
import com.springboot07mybatis.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;import java.util.List;/*** @author BoBooY* @date 2022/9/17 21:25*/
@RestController
public class UserController {@AutowiredUserMapper userMapper;@GetMapping("/getUsers")public List<User> getUsers() {List<User> users = userMapper.getUserList();for (User user : users) {System.out.println(user);}return users;}@GetMapping("/getUser/{id}")public User getUser(@PathVariable("id") int id) {User user = userMapper.getUserById(id);return user;}@GetMapping("/updateUser")public String updateUser() {User user = getUser(4);user.setName("laosi");user.setPwd("1234");int i = userMapper.updateUser(user);if(i > 0) {return "修改成功";} else {return "修改失败";}}@GetMapping("/addUser")public String addUser() {User user = new User();user.setName("老五");user.setPwd("123");int i = userMapper.addUser(user);if(i > 0) {return "添加成功";} else {return "添加失败";}}@GetMapping("/deleteUser/{id}")public String deleteUser(@PathVariable("id") int id) {int i = userMapper.deleteUser(id);if(i > 0) {return "删除成功";} else {return "删除失败";}}
}
  • 测试,功能正常,ok!

SpringBoot | SpringBoot整合数据库相关推荐

  1. SpringBoot (三) 整合数据库访问 jdbcTemplate、MyBatis

    哈喽,大家好,我是有勇气的牛排(全网同名)

  2. springboot JPA整合国产神通数据库(神州通用数据库)

    当前国产软件比较流行,就最近做过的springboot +JPA+神通数据库的项目做下记录供有需要的同学参考. 神通数据库在springboot中的配置和大多关系型数据库基本一样的,只是由于驱动jar ...

  3. springboot+security整合(1)

    说明 springboot 版本 2.0.3 源码地址:点击跳转 系列 springboot+security 整合(1) springboot+security 整合(2) springboot+s ...

  4. springboot下整合各种配置文件

    本博是在springboot下整合其他中间件,比如,mq,redis,durid,日志...等等  以后遇到再更.springboot真是太便捷了,让我们赶紧涌入到springboot的怀抱吧. ap ...

  5. springboot项目整合mybatis

    SpringBoot项目整合mybatis 本章内容 使用 idea创建 SpringBoot项目 SpringBoot项目中配制 mybatis 框架 1 创建 SpringBoot项目 1.1 在 ...

  6. SpringBoot 2 整合 Spring Session 最简操作

    SpringBoot 2 整合 SpringSession 前言 Spring Session 介绍 SpringBoot 快速整合 Spring Session Spring Session 测试 ...

  7. SpringBoot+Swagger整合API

    SpringBoot+Swagger整合API Swagger:整合规范的api,有界面的操作,测试 1.在pom.xml加入swagger依赖 <!--整合Swagger2配置类-->& ...

  8. Springboot -Shiro整合JWT(注解形式)

    Springboot -Shiro整合JWT(注解形式) 在这里只展示核心代码,具体的请访问github 参考timo 依赖导入 <dependencies><dependency& ...

  9. SpringBoot Data整合ElasticSearch

    SpringBoot Data整合ElasticSearch pom依赖 <!-- spring data和es的start依赖,会引入关联的elasticsearch-rest-high-le ...

最新文章

  1. 【 C 】最容易误判的优先级问题
  2. delphi中的dbgrid使用
  3. linux故障排除与修复(troubleshooting)
  4. mysql python is not installed_最全的解决安装MySQL-Python出现的问题: pip install MySQl-Python 出现:下列问题...
  5. [置顶]理解Linux系统负荷
  6. 实训项目四 powerpoint 综合应用_【深化改革结硕果】新疆番茄综合精深加工关键技术及产业化应用项目取得重大突破...
  7. 创业一定要做自己“喜欢”并且有“优势”的事情
  8. 修改disk驱动监控文件系统的IO特征
  9. Struts中DownloadAction的使用
  10. Banner设计文字如何排版,如何设计字体
  11. 二维码获取WIFI配置
  12. unity python做热更_Unity热更方案汇总
  13. At least one JAR was scanned for TLDs解决办法
  14. 1.学生党如何查找文献书籍
  15. android手机是vivo吗,为什么最流畅的安卓手机竟然是VIVO和OPPO?
  16. 读取云服务器文件列表,读取云服务器文件列表
  17. 位图(BMP)文件头格式及数据分析
  18. 采用74HC595驱动数码管实验
  19. 子网掩码和ip地址有效范围计算
  20. 通过u盘启动计算机使用ghost安装系统步骤,如何用u盘装ghost win7系统步骤

热门文章

  1. Python 网络爬虫基础知识及体验
  2. (07)FPGA硬件描述语言
  3. ui设计需要美术功底吗,没有美术功底如何快速提高
  4. 全球及中国液压机行业应用范围调研及投资策略预测报告2022-2028年
  5. linux 下搭建yolov3错误,yolov3---报段错误的可能原因及解决方法
  6. 最近我都干了些什么——反思!!
  7. 区块链培训中的Golang为什么这么重要?怎么学?
  8. Unity3D的特殊目录名称
  9. 腾讯回应微信读书侵害用户信息;苹果称今年新iPhone将推迟数周发布;Julia 1.6.0 发布| 极客头条
  10. 游戏:扫雷【C语言】