SpringBoot 集成 Mybatis

SpringBoot 集成 Mybatis 详细教程

(只有操作,没有理论,仅供参考学习)

一、操作部分

1. 准备数据库

1.1 数据库版本:

C:\WINDOWS\system32>mysql -V
mysql  Ver 8.0.25 for Win64 on x86_64 (MySQL Community Server - GPL)

1.2 启动 mysql 服务:

C:\WINDOWS\system32>net start mysql
The MySQL service is starting..
The MySQL service was started successfully.

1.3 新创建数据库 spring,并创建一个 user 表,user 表详情:

Column Name 		Datatype		PrimaryKey 		Unique
id     				  INT				√			  √
username			  VARCHAR(45)	
password			  VARCHAR(45)	

如下图:

SpringBoot 集成 Mybatis_第1张图片

2. 创建工程

2.1 使用 spring 官网页面创建工程(其他亦可),链接:Spring Initializr 创建 SpringBoot 工程,如下图:

SpringBoot 集成 Mybatis_第2张图片

2.2 用 IDEA 打开工程:

2.3 配置项目的 maven 环境:
File -> Setting... -> Maven

SpringBoot 集成 Mybatis_第3张图片
2.4 导入依赖 pom.xml 文件:

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
            <version>8.0.25version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>

注意点:由于我的项目运行有报错的原因,我把项目的版本调整了一下:
修正前:

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.13version>
        <relativePath/> 
    parent>

修正后:

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.4.2version>
        <relativePath/> 
    parent>

配置完成后完整的 pom.xml 文件


<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.4.2version>
        <relativePath/> 
    parent>
    <groupId>com.buzlgroupId>
    <artifactId>mainartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>mainname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
            <version>8.0.25version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

2.5 配置数据库连接文件 application.properties

注意点
第一行的数据库要修改为自己的数据库名称,我的数据库名称是 spring,根据实际需求更改
第二行和第三行是连接数据库的用户名和密码,根据实际需求更改
第四行是数据库的驱动,使用 com.mysql.cj.jdbc.Driver 还是 com.mysql.jdbc.Driver 按需更改
第五行是 mybatis mapper 文件路径,我的文件路径是:resources/mapper/UserMapper.xml,按需更改

spring.datasource.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml

2.6 创建 User.java 实体类

public class User {

    /**
     * 主键 id
     */
    private Integer id;

    private String username;

    private String password;
    
    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    /**
     * 重写 toString 方法
     * @return
     */
    @Override
    public String toString() {
        return "User{" +
                "id = " + id +
                "\t username = " + username +
                "\t password = " + password +
                "}";
    }
    // set and get method ...
}

2.7 创建 UserMapper 接口

@Mapper // 表示这是一个 Mybatis 的 mapper 类
@Repository
public interface UserMapper {

    @Autowired
    int insertUser(User user);
    
    @Autowired
    int deleteByPrimaryKey(Integer id);
    
    @Autowired
    User selectByPrimaryKey(Integer id);
    
    @Autowired
    int updateUserByPrimaryKey(User user);
    
    @Autowired
    List<User> selectAll();
    
}

2.8 创建 UserMapper 控制器

@RestController
@RequestMapping("/mybatis")
public class UserConroller {

    @Resource
    private UserMapper userMapper;

    @GetMapping("/selectAll")
    public List<User> selectAll() {
        List<User> userList = userMapper.selectAll();
        return userList;
    }

    @GetMapping("/selectByPrimaryKey")
    public User selectByPrimaryKey() {
        User user = userMapper.selectByPrimaryKey(111);
        return user;
    }

    @GetMapping("/insertSelective")
    public String insertUser() {
        User user = new User(123, "梅花", "pwd123");
        userMapper.insertUser(user);
        return "insert data to database success!";
    }

    @GetMapping("/updateByPrimaryKeySelective")
    public String updateUserByPrimaryKey() {
        Integer id = 123;
        User user = new User(id, "刘备", "pwd666");
        userMapper.updateUserByPrimaryKey(user);
        return "database updated success!";
    }

    @GetMapping("/deleteByPrimaryKey")
    public String deleteByPrimaryKey() {
        Integer id = 123;
        userMapper.deleteByPrimaryKey(id);
        return "delete database success!";
    }

}

2.6 UserMapper.xml 文件

注意点id 的值要和 UserMapper 接口的函数名称对应上
如:

 xml 文件 id 的值 selectAll 名字和 UserMapper 接口中的函数名一一对应
xml 文件:
<select id="selectAll" resultType="com.buzl.main.entity.User">

UserMapper 接口函数:
@Autowired
List<User> selectAll();
<?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.buzl.main.mapper.UserMapper">

    <!--共通属性抽出-->
    <sql id="Base_Column_List">
        id,username,password
    </sql>

    <!--查询数据库中所有的数据-->
    <select id="selectAll" resultType="com.buzl.main.entity.User">
        <!--select * from spring.user-->
        select <include refid="Base_Column_List" /> from spring.user
    </select>

    <!--通过 id 查询数据-->
    <select id="selectByPrimaryKey" resultType="com.buzl.main.entity.User">
        select <include refid="Base_Column_List" /> from spring.user where id=#{id}
    </select>

    <!--向数据库中插入数据-->
    <insert id="insertUser" parameterType="com.buzl.main.entity.User">
        insert into spring.user(<include refid="Base_Column_List" />) values(#{id},#{username},#{password})
    </insert>

    <!--更新数据库中的数据-->
    <update id="updateUserByPrimaryKey" parameterType="com.buzl.main.entity.User">
        update spring.user set username=#{username},password=#{password} where id=#{id}
    </update>

    <!--通过 id 删除数据-->
    <delete id="deleteByPrimaryKey" parameterType="Integer">
        delete from spring.user where id=#{id}
    </delete>

</mapper>

二、代码部分

1. 项目目录结构:

SpringBoot 集成 Mybatis_第4张图片

2. User 实体类

package com.buzl.main.entity;

/**
 * 实体类
 *
 * @author [email protected]
 * @data 2023-07-10
 */
public class User {

    /**
     * 主键 id
     */
    private Integer id;

    private String username;

    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    /**
     * 重写 toString 方法
     * @return
     */
    @Override
    public String toString() {
        return "User{" +
                "id = " + id +
                "\t username = " + username +
                "\t password = " + password +
                "}";
    }

}

3. UserController 控制器类

package com.buzl.main.controller;

import com.buzl.main.mapper.UserMapper;
import com.buzl.main.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * controller 实现
 *
 * @author [email protected]
 * @data 2023-07-10
 */
@RestController
@RequestMapping("/mybatis")
public class UserConroller {

    @Resource
    private UserMapper userMapper;

    /**
     * 查询数据操作
     *
     * @return
     */
    @GetMapping("/selectAll")
    public List<User> selectAll() {
        List<User> userList = userMapper.selectAll();
        System.out.println("数据库中所有的 user 数据 :" + userList);
        return userList;
    }

    /**
     * 通过 id 查询操作
     *
     * @return
     */
    @GetMapping("/selectByPrimaryKey")
    public User selectByPrimaryKey() {
        User user = userMapper.selectByPrimaryKey(111);
        System.out.println("通过 id 查询出来的 user : " + user);
        return user;
    }

    /**
     * 插入数据
     *
     * @return
     */
    @GetMapping("/insertSelective")
    public String insertUser() {
        User user = new User(123, "梅花", "pwd123");
        userMapper.insertUser(user);
        System.out.println("user :" + user + " 被成功插入数据库");
        return "insert data to database success!";
    }

    /**
     * 更新数据
     *
     * @return
     */
    @GetMapping("/updateByPrimaryKeySelective")
    public String updateUserByPrimaryKey() {
        Integer id = 123;
        User user = new User(id, "刘备", "pwd666");
        userMapper.updateUserByPrimaryKey(user);
        System.out.println("数据库中 id = " + id + " 的数据已经被更新了");
        return "database updated success!";
    }

    /**
     * 删除数据
     *
     * @return
     */
    @GetMapping("/deleteByPrimaryKey")
    public String deleteByPrimaryKey() {
        Integer id = 123;
        userMapper.deleteByPrimaryKey(id);
        System.out.println("数据库中 id = " + id + " 的 user 数据已经被删除了");
        return "delete database success!";
    }

}

4. UserMapper 接口

package com.buzl.main.mapper;

import com.buzl.main.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 接口类
 *
 * @author [email protected]
 * @data 2023-07-10
 */
@Mapper // 表示这是一个 Mybatis 的 mapper 类
@Repository
public interface UserMapper {

    /**
     * 向数据库中插入一条数据
     *
     * @param user
     * @return
     */
    @Autowired
    int insertUser(User user);

    /**
     * 通过主键 id 删除数据
     *
     * @param id
     * @return
     */
    @Autowired
    int deleteByPrimaryKey(Integer id);

    /**
     * 通过主键 id 删除数据库中的数据
     *
     * @param id
     * @return
     */
    @Autowired
    User selectByPrimaryKey(Integer id);

    /**
     * 通过主键 id 更新数据库中的数据
     *
     * @param user
     * @return
     */
    @Autowired
    int updateUserByPrimaryKey(User user);

    /**
     * 查询数据库中所有的数据
     *
     * @return
     */
    @Autowired
    List<User> selectAll();

}

5. 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.buzl.main.mapper.UserMapper">

    <!--共通属性抽出-->
    <sql id="Base_Column_List">
        id,username,password
    </sql>

    <!--查询数据库中所有的数据-->
    <select id="selectAll" resultType="com.buzl.main.entity.User">
        <!--select * from spring.user-->
        select <include refid="Base_Column_List" /> from spring.user
    </select>

    <!--通过 id 查询数据-->
    <select id="selectByPrimaryKey" resultType="com.buzl.main.entity.User">
        select <include refid="Base_Column_List" /> from spring.user where id=#{id}
    </select>

    <!--向数据库中插入数据-->
    <insert id="insertUser" parameterType="com.buzl.main.entity.User">
        insert into spring.user(<include refid="Base_Column_List" />) values(#{id},#{username},#{password})
    </insert>

    <!--更新数据库中的数据-->
    <update id="updateUserByPrimaryKey" parameterType="com.buzl.main.entity.User">
        update spring.user set username=#{username},password=#{password} where id=#{id}
    </update>

    <!--通过 id 删除数据-->
    <delete id="deleteByPrimaryKey" parameterType="Integer">
        delete from spring.user where id=#{id}
    </delete>

</mapper>

6. 数据库连接配置文件:

spring.datasource.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml

7. pom.xml 文件:

<?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.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.buzl</groupId>
    <artifactId>main</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>main</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--springboot 集成 mybatis,导入依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.25</version>
        </dependency>
        <!--jdbc连接数据库-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

三、测试

使用 ApiFox 工具进行测试(用浏览器也是一样)

  1. 查询数据库中所有的数据:

SpringBoot 集成 Mybatis_第5张图片

  1. 通过 id 查询数据库中的数据:

SpringBoot 集成 Mybatis_第6张图片

  1. 向数据库中插入数据:

SpringBoot 集成 Mybatis_第7张图片

SpringBoot 集成 Mybatis_第8张图片

  1. 通过 id 更改数据库中的数据

SpringBoot 集成 Mybatis_第9张图片

SpringBoot 集成 Mybatis_第10张图片

  1. 通过 id 删除数据库的数据
    SpringBoot 集成 Mybatis_第11张图片
    SpringBoot 集成 Mybatis_第12张图片
  2. 控制台打印信息:
数据库中所有的 user 数据 :[User{id = 111	 username = 张三	 password = pwd111}, User{id = 222	 username = 李四	 password = pwd222}]
数据库中所有的 user 数据 :[User{id = 111	 username = 张三	 password = pwd111}, User{id = 222	 username = 李四	 password = pwd222}]
通过 id 查询出来的 user : User{id = 111	 username = 张三	 password = pwd111}
user :User{id = 123	 username = 梅花	 password = pwd123} 被成功插入数据库
数据库中所有的 user 数据 :[User{id = 111	 username = 张三	 password = pwd111}, User{id = 123	 username = 梅花	 password = pwd123}, User{id = 222	 username = 李四	 password = pwd222}]
数据库中 id = 123 的数据已经被更新了
数据库中所有的 user 数据 :[User{id = 111	 username = 张三	 password = pwd111}, User{id = 123	 username = 刘备	 password = pwd666}, User{id = 222	 username = 李四	 password = pwd222}]
数据库中 id = 123 的 user 数据已经被删除了
数据库中所有的 user 数据 :[User{id = 111	 username = 张三	 password = pwd111}, User{id = 222	 username = 李四	 password = pwd222}]

这是结束标志,结束了 ~

你可能感兴趣的:(Spring,spring,boot,mybatis,后端)