Mybatis快速创建项目(新人入职)

一、数据库设计与创建

首先创建一个简单的用户表,用于演示 CRUD 操作。

-- 创建数据库
CREATE DATABASE mybatis_demo;

-- 使用数据库
USE mybatis_demo;

-- 创建用户表
CREATE TABLE user (
    id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '用户ID',
    username VARCHAR(50) NOT NULL COMMENT '用户名',
    password VARCHAR(100) NOT NULL COMMENT '密码',
    email VARCHAR(100) DEFAULT NULL COMMENT '邮箱',
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
);

-- 插入测试数据
INSERT INTO user (username, password, email) VALUES
('test1', '123456', 'test1@example.com'),
('test2', '123456', 'test2@example.com'),
('test3', '123456', 'test3@example.com');

二、创建 Spring Boot 项目

1. 使用 Spring Initializr 初始化项目

访问 Spring Initializr,配置以下参数:

  • Project:Maven Project
  • Language:Java
  • Spring Boot:3.0.x (或最新稳定版)
  • Group:com.example
  • Artifact:mybatis-demo
  • Dependencies
    • Spring Web
    • Spring Data JPA (可选,用于对比)
    • MyBatis Framework
    • MySQL Driver
    • Lombok (可选,简化代码)

点击 Generate 下载项目压缩包,解压后导入 IDE。

2. 添加依赖(如果手动创建)

在 pom.xml 中确保以下依赖存在:

xml

<dependencies>
    <!-- Spring Boot 核心 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <!-- MyBatis 集成 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>3.0.1</version>
    </dependency>
    
    <!-- MySQL 驱动 -->
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    
    <!-- Lombok (可选) -->
    <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>

三、配置数据源与 MyBatis

在 src/main/resources/application.properties 中添加数据库配置:

properties

# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml  # Mapper XML 文件位置
mybatis.type-aliases-package=com.example.mybatisdemo.entity  # 实体类包路径
mybatis.configuration.map-underscore-to-camel-case=true  # 开启驼峰命名转换

四、创建实体类

在 src/main/java/com/example/mybatisdemo/entity 目录下创建 User 类:

java

package com.example.mybatisdemo.entity;

import lombok.Data;

import java.util.Date;

@Data  // Lombok 注解,自动生成 getter/setter/toString 等
public class User {
    private Long id;
    private String username;
    private String password;
    private String email;
    private Date createTime;
}

五、创建 Mapper 接口

在 src/main/java/com/example/mybatisdemo/mapper 目录下创建 UserMapper 接口:

java

package com.example.mybatisdemo.mapper;

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

import java.util.List;

@Mapper  // MyBatis Mapper 注解
public interface UserMapper {
    
    // 查询所有用户
    List<User> selectAll();
    
    // 根据 ID 查询用户
    User selectById(@Param("id") Long id);
    
    // 插入用户
    int insert(User user);
    
    // 更新用户
    int update(User user);
    
    // 删除用户
    int deleteById(@Param("id") Long id);
}

六、创建 Mapper XML 文件

在 src/main/resources/mapper 目录下创建 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.example.mybatisdemo.mapper.UserMapper">
    
    <!-- 查询所有用户 -->
    <select id="selectAll" resultType="User">
        SELECT * FROM user
    </select>
    
    <!-- 根据 ID 查询用户 -->
    <select id="selectById" resultType="User">
        SELECT * FROM user WHERE id = #{id}
    </select>
    
    <!-- 插入用户 -->
    <insert id="insert" parameterType="User">
        INSERT INTO user (username, password, email, create_time)
        VALUES (#{username}, #{password}, #{email}, #{createTime})
    </insert>
    
    <!-- 更新用户 -->
    <update id="update" parameterType="User">
        UPDATE user
        SET username = #{username},
            password = #{password},
            email = #{email}
        WHERE id = #{id}
    </update>
    
    <!-- 删除用户 -->
    <delete id="deleteById" parameterType="Long">
        DELETE FROM user WHERE id = #{id}
    </delete>
</mapper>

七、创建 Service 层

在 src/main/java/com/example/mybatisdemo/service 目录下创建 UserService 接口及实现类:

java

// UserService.java
package com.example.mybatisdemo.service;

import com.example.mybatisdemo.entity.User;

import java.util.List;

public interface UserService {
    List<User> getAllUsers();
    User getUserById(Long id);
    int createUser(User user);
    int updateUser(User user);
    int deleteUser(Long id);
}

// UserServiceImpl.java
package com.example.mybatisdemo.service.impl;

import com.example.mybatisdemo.entity.User;
import com.example.mybatisdemo.mapper.UserMapper;
import com.example.mybatisdemo.service.UserService;
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 List<User> getAllUsers() {
        return userMapper.selectAll();
    }
    
    @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);
    }
}

八、创建 Controller 层

在 src/main/java/com/example/mybatisdemo/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("/api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    // 获取所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    
    // 根据 ID 获取用户
    @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);
    }
}

九、启动应用并测试

  1. 在 src/main/java/com/example/mybatisdemo 目录下找到主应用类 MybatisDemoApplication,添加 @MapperScan 注解:

java

package com.example.mybatisdemo;

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

@SpringBootApplication
@MapperScan("com.example.mybatisdemo.mapper")  // 扫描 Mapper 接口
public class MybatisDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisDemoApplication.class, args);
    }
}
  1. 运行主类启动应用,访问以下接口测试:
  • 获取所有用户
    GET http://localhost:8080/api/users

  • 获取单个用户
    GET http://localhost:8080/api/users/1

  • 创建用户
    POST http://localhost:8080/api/users
    请求体:

    json

    {
      "username": "test4",
      "password": "123456",
      "email": "test4@example.com"
    }
    
  • 更新用户
    PUT http://localhost:8080/api/users/1
    请求体:

    json

    {
      "username": "updated",
      "email": "updated@example.com"
    }
    
  • 删除用户
    DELETE http://localhost:8080/api/users/1

十、项目结构总结

plaintext

mybatis-demo/
├── src/main/java/
│   └── com/example/mybatisdemo/
│       ├── MybatisDemoApplication.java    # 主应用类
│       ├── controller/                    # 控制器层
│       │   └── UserController.java
│       ├── entity/                        # 实体类
│       │   └── User.java
│       ├── mapper/                        # Mapper 接口
│       │   └── UserMapper.java
│       └── service/                       # 服务层
│           ├── UserService.java
│           └── impl/
│               └── UserServiceImpl.java
└── src/main/resources/
    ├── application.properties             # 配置文件
    └── mapper/                            # Mapper XML 文件
        └── UserMapper.xml

十一、常见问题与解决方案

  1. 找不到 Mapper 接口

    • 确保 @MapperScan 注解路径正确
    • 或在每个 Mapper 接口上添加 @Mapper 注解
  2. 数据库连接失败

    • 检查数据库用户名、密码、URL 是否正确
    • 确保 MySQL 服务已启动
  3. 字段映射问题

    • 确保 map-underscore-to-camel-case=true
    • 或在 XML 中使用 <resultMap> 显式映射
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值