前言:
小伙伴们,大家好,我是狂奔の蜗牛rz,当然你们可以叫我蜗牛君,我是一个学习Java半年多时间的小菜鸟,同时还有一个伟大的梦想,那就是有朝一日,成为一个优秀的Java架构师。 这个SpringBoot基础学习系列用来记录我学习SpringBoot框架基础知识的全过程 (这个系列是参照B站狂神的SpringBoot最新教程来写的,由于是之前整理的,但当时没有发布出来,所以有些地方可能有错误,希望大家能够及时指正!) 之后我将会以一天一更的速度更新这个系列,还没有学习SpringBoot的小伙伴可以参照我的博客学习一下;当然学习过的小伙伴,也可以顺便跟我一起复习一下基础。 最后,希望能够和大家一同进步吧!加油吧!少年们!
废话不多说,让我们开始今天的学习内容吧,由于今天我们来到了SpringBoot基础学习的第八站:整合Mybatis框架!
6.3 整合Mybatis框架
6.3.1 搭建项目基本环境
1.创建Spring Boot项目
- 设置项目基本信息,设置Group、Artifact和Java Vesrion等
- 引入项目资源依赖,Spring Web、JDBC API和MySQL Driver等
2.引入Mybatis和Lombok资源依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/>
</parent>
<groupId>com.kuang</groupId>
<artifactId>springboot-05-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-05-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.连接MySQL数据库
3-1 编写applicationContext核心配置文件
# 配置数据库相关属性
# 数据库用户登录名
spring.datasource.username=root
# 数据库登录密码
spring.datasource.password=123456
# 数据库url连接
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
# 数据库驱动名
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 配置Tomcat服务器端口号
server.port=8888
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
server:
port: 8888
3-2 连接MySQL数据库
3-3 数据库连接失败解决方案
测试连接过程中遇到了:
解决方法:设置MySQL数据库的时区
1.连接mysql
mysql -u root -p
2.查看系统默认的时区
show variables like'%time_zone';
3.设置新的时区
set global time_zone = '+8:00';
4.查看修改后的时区
这里注意要退出命令窗口后重新进入才可以看到修改成功后的时区
show variables like'%time_zone';
4.查看默认数据源和连接
package com.kuang;
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.SQLException;
@SpringBootTest
class Springboot05MybatisApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
6.3.2 完善项目基本环境
1.项目基本结构和修改配置文件
1-1 项目基本结构
1-2 修改核心配置文件
# 配置数据库相关属性
# 数据库用户登录名
spring.datasource.username=root
# 数据库登录密码
spring.datasource.password=123456
# 数据库url连接
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
# 数据库驱动名
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 配置Tomcat服务器端口号
server.port=8888
# 配置mybatis相关属性
# 通过包设置别名
mybatis.type-aliases-package=com.kuang.pojo
# 设置mapper映射文件的位置
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# 不要再mybatis/mapper/*.xml前加上/,否则将会到项目根目录下开始找
# mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml
2.编写User实体类和UserMapper接口
2-1 编写User实体类
package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}
2-2 编写UserMapper接口
package com.kuang.mapper;
import com.kuang.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Mapper
@Repository
public interface UserMapper {
public List<User> getUserList();
public User getUserById(int id);
public int addUser(User user) ;
public int deleteUser(int id);
public int updateUser(User user);
}
2-3 编写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.kuang.mapper.UserMapper">
<select id="getUserList" resultType="com.kuang.pojo.User">
Select * from mybatis.user
</select>
<select id="getUserById" resultType="com.kuang.pojo.User" parameterType="int">
Select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="User">
Insert into mybatis.user(id, name, pwd)
values (#{id}, #{name}, #{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
Delete from mybatis.user where id = #{id}
</delete>
<update id="updateUser" parameterType="User">
Update mybatis.user set name=#{name}, pwd=#{pwd}
where id = #{id}
</update>
</mapper>
3.编写UserMapper映射文件和UserController控制器
3-1 编写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.kuang.mapper.UserMapper">
<select id="getUserList" resultType="com.kuang.pojo.User">
Select * from mybatis.user
</select>
<select id="getUserById" resultType="com.kuang.pojo.User" parameterType="int">
Select * from mybatis.user where id = #{id}
</select>
<insert id="addUser" parameterType="User">
Insert into mybatis.user(id, name, pwd)
values (#{id}, #{name}, #{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
Delete from mybatis.user where id = #{id}
</delete>
<update id="updateUser" parameterType="User">
Update mybatis.user set name=#{name}, pwd=#{pwd}
where id = #{id}
</update>
</mapper>
3-2 编写UserController控制器类
package com.kuang.controller;
import com.kuang.mapper.UserMapper;
import com.kuang.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.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/getList")
public List<User> getUserList() {
List<User> users = userMapper.getUserList();
for (User user : users) {
System.out.println(user);
}
return users;
}
@GetMapping("/getUser2")
public User getUserById() {
User user = userMapper.getUserById(1);
System.out.println(user);
return user;
}
@GetMapping("/getUser")
public User getUserById2(int id) {
User user = userMapper.getUserById(id);
System.out.println(user);
return user;
}
@GetMapping("/getUser/{userId}")
public User getUserById3(@PathVariable("userId") int id) {
User user = userMapper.getUserById(id);
System.out.println(user);
return user;
}
@GetMapping("/addUser")
public String addUser() {
User user = new User();
user.setId(6);
user.setName("张碧晨");
user.setPwd("zbc123456");
userMapper.addUser(user);
return "addUser-OK";
}
@GetMapping("/deleteUser/{userId}")
public String deleteUser(@PathVariable("userId") int id) {
userMapper.deleteUser(id);
return "deleteUser-OK";
}
@GetMapping("/updateUser/{userId}")
public String updateUser(@PathVariable("userId") int id) {
User user = new User();
user.setName("薛之谦");
user.setPwd("xzq123456");
user.setId(id);
userMapper.updateUser(user);
return "updateUser-OK";
}
}
4.增删改查操作和测试结果
4-1 查询所有用户信息
4-2 通过Id查询指定用户信息
-
页面请求 使用常规风格: 使用RestFul风格:
4-3 增加用户信息
4-4 删除用户信息
4-5 修改用户信息
好了,今天的有关 SpringBoot基础学习之整合Mybatis框架 的学习就到此结束啦,欢迎小伙伴们积极学习和讨论,喜欢的可以给蜗牛君点个关注,顺便来个一键三连,我们下期见,拜拜啦!
参考视频链接:https://www.bilibili.com/video/BV1PE411i7CV(【狂神说Java】SpringBoot最新教程IDEA版通俗易懂)
|