SpringBoot中使用MyBatis入门笔记

第一步:准备数据库以及数据

  1. 略过安装数据库操作以及创建数据库操作
  2. 创建tb_user表
  3. 初始化数据

第二步:准备Maven工程

1、使用idea创建一个maven工程

工程名:我使用的是springandmybatis

选择maven

选择JDK17或者以上的版本

groupid:也就是包名,我写的是com.test

2、添加依赖,在pom.xml文件中添加依赖(注意几个添加注释的地方),添加后记得同步

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--  1、添加SpringBoot parent  -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.5.4</version>
    </parent>

    <groupId>com.test</groupId>
    <artifactId>springandmybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <!-- 2、添加SpringBoot Web Starter -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!-- 3、添加Mybatis Starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>

        <!-- 3、添加MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
    </dependencies>

</project>

3.添加配置文件(在resources目录下,添加application.yaml文件)

yaml 复制代码
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=false&autoReconnect=true
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

# 这种方式比较简单
mybatis:
  mapper-locations: classpath:mapper/*.xml

第三步:编写代码

  1. 编写UserModel类,其作用是对应数据库表tb_user
java 复制代码
package com.test.model;

public class UserModel {
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    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 String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
}
  1. 编写UserMapper接口(注意:在类上面添加了@Repository注解)
java 复制代码
package com.test.mapper;

import com.test.model.UserModel;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface UserMapper {
    /**
     * 查询所有用户
     * @return
     */
    List<UserModel> selectAll();

    /**
     * 插入用户
     * @param userModel
     * @return
     */
    Integer insertUser(UserModel userModel);
}
  1. 编写userMapper.xml 在resources目录中创建mapper目录,用来专门存放mapper的xml文件,这里暂时先创建userMapper.xml
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.test.mapper.UserMapper">

    <!-- 插入User -->
    <insert id="insertUser" parameterType="com.test.model.UserModel">
        INSERT INTO tb_user(username, password, gender, addr) VALUES(#{username}, #{password}, #{gender}, #{addr})
    </insert>

    <!-- 查询所有User -->
    <select id="selectAll" resultType="com.test.model.UserModel">
        SELECT * FROM tb_user
    </select>
</mapper>
  1. 编写UserService类(注意:在类上面添加了@Service注解)
java 复制代码
package com.test.service;

import com.test.mapper.UserMapper;
import com.test.model.UserModel;
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 UserService {

    private final UserMapper userMapper;

    @Autowired // 构造器注入推荐
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List<UserModel> selectAll() {
        return userMapper.selectAll();
    }

    public int insertUser(UserModel user) {
        return userMapper.insertUser(user);
    }
}
  1. 编写UserController类(注意:在类上面添加了@RestController注解)
ini 复制代码
package com.test.controller;

import com.test.model.UserModel;
import com.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping(path="/all")
    public @ResponseBody Iterable<UserModel> getAllUsers() {
        return userService.selectAll();
    }

    @GetMapping(path="/add")
    public @ResponseBody Iterable<UserModel> addUser() {
        String username = "张三";
        String password = "123456";
        String gender="1";
        String addr = "上海";
        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setGender(gender);
        userModel.setAddr(addr);
        userService.insertUser(userModel);
        return userService.selectAll();
    }
}
  1. 编写程序入口类(注意:在类名上添加了@SpringBootApplication@MapperScan("com.test.mapper")两个注解)
java 复制代码
package com.test;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.test.mapper")
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

第四步:测试

运行入口类,如果没有错误,就可以使用浏览器请求UserController中定义的两个接口

  1. 查询所有

2. 插入数据

相关推荐
东宇科技1 分钟前
用CladueCode来玩tp8+swoole(常用案例)
后端·swoole
Shadow(⊙o⊙)6 分钟前
硬核手搓解析!进程-内核分析:命令行参数及环境变量,重构main()
linux·运维·服务器·开发语言·c++·后端·学习
毋语天9 分钟前
Claude Code 完整安装与配置指南(含 CC-Switch 多供应商切换工具)
后端·python·ai编程
StackNoOverflow11 分钟前
RabbitMQ 入门详解(含安装 + 配置 + 管理后台)
开发语言·后端·ruby
养肥胖虎9 小时前
Docker学习笔记:后端、数据库和反向代理怎么一起跑起来
后端·nginx·docker·postgresql·go·部署
晓杰'10 小时前
从0到1实现 Balatro 游戏后端(2):NestJS框架搭建与项目结构设计
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
无所事事O_o10 小时前
二次验证码TOTP 使用说明
后端·二次验证码·谷歌验证器
ltl10 小时前
Multi-Head Attention:为什么要分多个头
后端
ltl11 小时前
Scaled Dot-Product:那个根号 d_k 是怎么来的'
后端
折哥的程序人生 · 物流技术专研13 小时前
《Java 100 天进阶之路》第17篇:Java常用包装类与自动装箱拆箱深入
java·开发语言·后端·面试