当前位置: 首页 > article >正文

Spring Boot 整合 MyBatis 快速入门超详教程

目标:

为了快速入门,我这里演示创建一个简单的用户管理,包含用户列表的增删改查功能。

准备工作:

1 环境搭建: 确保已安装 JDK 1.8+、Maven 3.3+、MySQL 数据库以及 IntelliJ IDEA 。

2 数据库准备: 在 MySQL 中创建名为 user_db 的数据库,并在其中创建名为 user 的表,包含以下字段:

                a) id: 用户 ID,主键,自增

                b) name: 用户名,字符串类型

                c) age: 年龄,整数类型

 建表SQL语句:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    age INT NOT NULL
);

3 创建 Spring Boot 项目: 使用 IDEA 创建一个名为 mybatis-demo 的 Spring Boot 项目,并添加以下依赖:

                a) Spring Web

                b) MyBatis Framework

                c) MySQL Driver

相关教程:

JDK安装教程及Java环境配置

MySql安装教程

MySql基础语法详解

IDEA安装教程

快速创建Spring Boot教程


详细步骤:

1. 项目结构:

mybatis-demo
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── mybatisdemo
│   │   │               ├── MybatisDemoApplication.java
│   │   │               ├── controller
│   │   │               │   └── UserController.java
│   │   │               ├── entity
│   │   │               │   └── User.java
│   │   │               ├── mapper
│   │   │               │   └── UserMapper.java
│   │   │               └── service
│   │   │                   ├── UserServiceImpl.java
│   │   │                   └── UserService.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── mapper
│   │           └── UserMapper.xml
│   └── test
│       └── java
│           └── com
│               └── example
│                   └── mybatisdemo
│                       └── MybatisDemoApplicationTests.java
└── pom.xml

2. 引入依赖 (pom.xml):

<?xml version="1.0" encoding="UTF-8"?>
<project ...>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.7.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>runtime</scope>
    </dependency>
  </dependencies>
</project>

3. 配置数据源 (application.properties):

spring.datasource.url=jdbc:mysql://localhost:3306/user_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

4. 创建实体类 (User.java):

package com.example.mybatisdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    // Getters and Setters 省略
}

5. 创建 Mapper 接口 (UserMapper.java):

package com.example.mybatisdemo.mapper;

import com.example.mybatisdemo.entity.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(@Param("id") Long id);

    @Insert("INSERT INTO user(name, age) VALUES (#{name}, #{age})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(User user);

    @Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
    int update(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    int deleteById(@Param("id") Long id);

    @Select("SELECT * FROM user")
    List<User> selectAllUsers();
}

@Mapper 注解告诉 MyBatis 创建这个接口的实现类。

  • @Select、@Insert、@Update 和 @Delete 注解分别对应 SQL 语句的查询、插入、更新和删除操作。

  • @Param("id") 将方法参数 id 绑定到 SQL 语句中的占位符 #{id}。

  • @Options 配置插入操作,useGeneratedKeys = true 表示使用数据库生成的主键,keyProperty = "id" 表示将生成的主键赋值给实体类 User 的 id 属性。

6. 创建 Mapper XML 文件 (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.example.mybatisdemo.mapper.UserMapper">

    <!-- 根据 ID 查询用户 -->
    <select id="selectById" resultType="com.example.mybatisdemo.entity.User">
        SELECT * FROM user WHERE id = #{id}
    </select>

    <!-- 新增用户 -->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        INSERT INTO user(name, age) VALUES (#{name}, #{age})
    </insert>

    <!-- 更新用户信息 -->
    <update id="update">
        UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
    </update>

    <!-- 根据 ID 删除用户 -->
    <delete id="deleteById">
        DELETE FROM user WHERE id = #{id}
    </delete>

    <!-- 查询所有用户 -->
    <select id="selectAllUsers" resultType="com.example.mybatisdemo.entity.User">
        SELECT * FROM user
    </select>

</mapper>

解释:

  • <mapper namespace="com.example.mybatisdemo.mapper.UserMapper">: 定义了这个 Mapper XML 文件对应的 Mapper 接口的全限定名。

  • <select>, <insert>, <update>, <delete>: 分别对应 SQL 语句的查询、插入、更新和删除操作。

  • id 属性: 与 Mapper 接口中定义的方法名一致。

  • resultType 属性: 定义查询结果的类型,这里对应 com.example.mybatisdemo.entity.User。

  • #{id}: 使用占位符传入参数。

  • keyProperty="id" 和 useGeneratedKeys="true": 用于获取插入操作后自动生成的主键,并将主键值赋值给实体类的 id 属性。

注意:

  • Mapper XML 文件需要放在 resources/mapper 目录下。

  • Mapper XML 文件名建议与 Mapper 接口名一致,例如 UserMapper.xml。

7. 创建 Service 接口 (UserService.java):

package com.example.mybatisdemo.service;

import com.example.mybatisdemo.entity.User;

import java.util.List;

public interface UserService {
    User getUserById(Long id);

    int createUser(User user);

    int updateUser(User user);

    int deleteUser(Long id);

    List<User> getAllUsers();
}

8. 实现 Service 接口 (UserServiceImpl.java):

package com.example.mybatisdemo.service;

import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public int createUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.update(user);
    }

    @Override
    public int deleteUser(Long id) {
        return userMapper.deleteById(id);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }
}

@Service 注解将该类标记为 Spring Bean。

  • @Autowired 注解自动注入 UserMapper 实例。

9. 创建 Controller (UserController.java):

package com.example.mybatisdemo.controller;

import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

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

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @PostMapping
    public int createUser(@RequestBody User user) {
        return userService.createUser(user);
    }

    @PutMapping("/{id}")
    public int updateUser(@PathVariable Long id, @RequestBody User user) {
        user.setId(id);
        return userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public int deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
}

@RestController 注解将该类标记为 RESTful 风格的控制器。

  • @RequestMapping("/users") 定义接口路径前缀。

  • @GetMapping、@PostMapping、@PutMapping、@DeleteMapping 分别对应 GET、POST、PUT、DELETE 请求。

10. 运行项目:

  • 运行 MybatisDemoApplication.java 启动 Spring Boot 应用。

11. 测试接口:

  • 使用 Postman 或浏览器测试以下接口:

    • GET /users: 获取所有用户

    • GET /users/1: 获取 ID 为 1 的用户

    • POST /users: 创建新用户 (请求体: {"name": "John Doe", "age": 30})

    • PUT /users/1: 更新 ID 为 1 的用户信息 (请求体: {"name": "Jane Doe", "age": 25})

    • DELETE /users/1: 删除 ID 为 1 的用户

通过以上步骤,你已经成功创建了一个使用 Spring Boot 和 MyBatis 实现的简单用户管理。

进阶学习:

  • MyBatis 动态 SQL

  • MyBatis 缓存机制

  • MyBatis 一对一、一对多、多对多关联查询

希望这个超详细的教程能够帮助各位看官快速入门 Spring Boot 和 MyBatis!感谢各位看官的观看,下期见,谢谢~


http://www.kler.cn/news/354910.html

相关文章:

  • 设计模式04-创建型模式1(简单工厂/工厂模式/抽象工厂/Java)
  • 敏捷Scrum项目管理方法,如何做好敏捷项目管理❓
  • 距离上次发文已经十个多月了
  • linux svn命令简单使用
  • 面试会问到的AI 算法题(二)
  • postgresql是国产数据库吗?
  • 4.8 大数据发展趋势
  • 春日编程助手:Spring Boot课程答疑服务
  • 大数据治理:全面提升数据资产价值
  • TSmaster CAN的E2E检验配置
  • Centos7安装ZLMediaKit
  • 【Spring】@Autowired注解自动装配的过程
  • 二、数据离线处理场景化解决方案
  • 【AI大模型】尝试 Google Gemma 模型 MacOS 本地部署
  • HTTP代理的优点和局限性
  • 华为国际云:全球领先的云服务解决方案
  • .net core 实现多线程方式有哪些
  • spring 如何解决循环依赖
  • 《米小圈动画成语》|在趣味中学习,在快乐中掌握成语知识!
  • C++11新特性(4)