02 - SpringBoot中级
本章目录
- SpringBoot整合JdbcTemplate
- SpringBoot整合MyBatis
- SpringBoot整合MyBatis-Plus
- 分页插件的集成
1.0 SpringBoot整合JdbcTemplate
Spring Framework对数据库的操作在JDBC上面做了深层次的封装,通过依赖注入功能,可以将 DataSource 注册到JdbcTemplate之中,使我们可以轻易的完成对象关系映射,并有助于规避常见的错误,在SpringBoot中我们可以很轻松的使用它。
特点:
- 速度快,对比其它的ORM框架而言,JDBC的方式无异于是最快的
- 配置简单,Spring自家出品,几乎没有额外配置
置 - 学习成本低,毕竟JDBC是基础知识,JdbcTemplate更像是一个DBUtils
1.1 整合JdbcTemplate
在 pom.xml
中添加对 JdbcTemplate
的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
在application.properties
中添加如下配置。值得注意的是,SpringBoot默认会自动配置DataSource
,它将优先采用HikariCP
连接池,如果没有该依赖的情况则选取tomcat-jdbc
,如果前两者都不可用最后选取Commons DBCP2
。通过spring.datasource.type属性可以指定其它种类的连接池
# 数据源
spring:
datasource:
url: jdbc:mysql:///boot?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password:
启动项目,通过日志,可以看到默认情况下注入的是HikariDataSource
2022-11-16 09:14:46.329 INFO 16472 --- [ main] com.xja.Day03Application : Starting Day03Application using Java 1.8.0_201 on DESKTOP-TTS40QH with PID 16472 (E:\课程记录\T6\03-SpringBoot整合\day03\target\classes started by lenovo in E:\课程记录\T6\03-SpringBoot整合\day03)
2022-11-16 09:14:46.336 INFO 16472 --- [ main] com.xja.Day03Application : No active profile set, falling back to 1 default profile: "default"
2022-11-16 09:14:47.614 INFO 16472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2022-11-16 09:14:47.624 INFO 16472 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 5 ms. Found 0 JDBC repository interfaces.
2022-11-16 09:14:48.329 INFO 16472 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-11-16 09:14:48.342 INFO 16472 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-11-16 09:14:48.342 INFO 16472 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68]
2022-11-16 09:14:48.559 INFO 16472 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-11-16 09:14:48.560 INFO 16472 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2156 ms
2022-11-16 09:14:48.977 WARN 16472 --- [ main] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates, check your Thymeleaf configuration, or set spring.thymeleaf.check-template-location=false)
2022-11-16 09:14:49.090 INFO 16472 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-11-16 09:14:49.283 INFO 16472 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-11-16 09:14:49.586 INFO 16472 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-11-16 09:14:49.596 INFO 16472 --- [ main] com.xja.Day03Application : Started Day03Application in 4.047 seconds (JVM running for 7.288)
1.2 案例测试
创建一张 t_user
的表
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(1) DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
实体类
package com.xja.entity;
import lombok.Data;
@Data
public class Student {
private Integer id;
private String name;
private int age;
private String description;
}
控制层
package com.xja.controller;
import java.util.List;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
/**
* 查询
*/
@RequestMapping("queryStudentList")
public String queryStudentList(Model model){
List<Student> list = studentService.queryStudentList();
model.addAttribute("list",list);
return "student_list";
}
/**
* 增加跳转
*/
@RequestMapping("/toAdd")
public String toAdd(){
return "student_add";
}
/**
* 增加
*/
@RequestMapping("/saveStudent")
public String saveStudent(Student student){
studentService.saveStudent(student);
return "redirect:/student/queryStudentList";
}
@RequestMapping("/deleteStudent")
public String deleteStudent(Integer id){
studentService.deleteStudent(id);
return "redirect:/student/queryStudentList";
}
}
业务层省略->持久化层
package com.xja.dao;
import java.util.List;
@Repository //老实持久层的标记 同 @Controller @Service 一起的
public class StudentDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Student> queryStudentList() {
String sql = "select * from student";
List<Student> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Student.class));
return list;
}
//单个对象 queryForObject
public void saveStudent(Student student) {
String sql = "insert into student (name,age,description) value (?,?,?)";
jdbcTemplate.update(sql,student.getName(),student.getAge(),student.getDescription());
}
public void deleteStudent(Integer id) {
String sql = "delete from student where id = ?";
jdbcTemplate.update(sql,id);
}
}
查询页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script>
<script>
$(function () {
$("#save").click(function () {
window.location = "toAdd";
})
})
function deletes(id){
alert(id);
}
</script>
</head>
<body>
<button class="btn btn-success" id="save">增加</button>
<table class="table table-bordered" style="width: 800px">
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>描述</th>
<th>操作</th>
</tr>
<tr th:each="stu,i:${list}">
<td th:text="${i.count}"></td>
<td th:text="${stu.name}"></td>
<td th:text="${stu.age}"></td>
<td th:text="${stu.description}"></td>
<td>
<button class="btn btn-sm btn-danger" th:onclick="|deletes(${stu.id})|">删除</button>
<a th:href="|deleteStudent?id=${stu.id}|">删除</a>
</td>
</tr>
</table>
</body>
</html>
效果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xZxCmMa8-1668683830489)(images/TlVz6Nv0enOIGdLDmJuhCqSw5wT8yWjQeeEQUJzQ52Q.png)]
2.0 SpringBoot整合MyBatis
2.1 构建项目
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-S9FRi8Y3-1668683830490)(images/xJRg9_mqMAmy3TfT8a_Nx9tJfHK4uXdZ9OKa-rmQew0.png)]
启动
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wfvH9w6G-1668683830491)(images/MwKissBG6NwU_kQ26aRj3RfNsSBr5It6PVsxiCqc_x0.png)]
原因:没有配置数据源
# 数据源
spring:
datasource:
url: jdbc:mysql:///boot?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password:
type: com.zaxxer.hikari.HikariDataSource
hikari:
# 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
connection-timeout: 30000
# 最小连接数
minimum-idle: 5
# 最大连接数
maximum-pool-size: 20
# 事务自动提交
auto-commit: true
# 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
idle-timeout: 600000
# 连接池名字
pool-name: DateSourceHikariCP
# 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
max-lifetime: 1800000
#配置
mybatis:
type-aliases-package: com.xja.entity
#如果文件接口和mapper名字及路径都相同则可以省略,否则加上
mapper-locations: classpath*:/mapper/*.xml
dao 转化为 mapper
@Mapper
public interface StudentMapper {
List<Student> queryStudentList();
void saveStudent(Student student);
void deleteStudent(Integer id);
}
mapper
<?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.xja.mapper.StudentMapper">
<insert id="saveStudent" parameterType="com.xja.entity.Student">
insert into student (name,age,description) value (#{name},#{age},#{description})
</insert>
<delete id="deleteStudent" parameterType="integer">
delete from student where id = #{id}
</delete>
<select id="queryStudentList" resultType="com.xja.entity.Student">
select * from student
</select>
</mapper>
3.0 SpringBoot整合MyBatis-Plus
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LfZ9sg8l-1668683830492)(images/_ZAh4lELV0uvYCX7eg_uymLDb0A7h8sVdhKvftuB0fc.png)]
依赖 mybatis plus 部分依赖
<!-- mp -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 代码生成工具 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 代码生成模板 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
代码生成器
配置文件
# 数据源
spring:
datasource:
url: jdbc:mysql:///boot?useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password:
type: com.zaxxer.hikari.HikariDataSource
hikari:
# 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 默认:30秒
connection-timeout: 30000
# 最小连接数
minimum-idle: 5
# 最大连接数
maximum-pool-size: 20
# 事务自动提交
auto-commit: true
# 连接超时的最大时长(毫秒),超时则被释放(retired),默认:10分钟
idle-timeout: 600000
# 连接池名字
pool-name: DateSourceHikariCP
# 连接的生命时长(毫秒),超时而且没被使用则被释放(retired),默认:30分钟 1800000ms
max-lifetime: 1800000
#添加mybatis-plus配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印SQL执行详情
type-aliases-package: com.xja.entity