Java开发实战:使用IntelliJ IDEA 开发Spring Boot + MyBatis + MySQL的详细实现步骤
使用IntelliJ IDEA 开发Spring Boot + MyBatis + MySQL的详细实现步骤
在本文中,我们将一步步讲解如何在IntelliJ IDEA 2024.2.3中使用Spring Boot、MyBatis和MySQL来开发一个简单的Web应用。通过本文,你将学会如何设置项目、配置数据库、创建实体类、编写Mapper接口、实现服务逻辑,以及如何测试你的API。让我们开始吧!
1. 安装IntelliJ IDEA
首先,确保你安装了IntelliJ IDEA 。根据实际选择IntelliJ IDEA 版本,我安装的是IntelliJ IDEA2024.2.3,如果尚未安装,可以从官方网站下载并安装:
- IntelliJ IDEA 官方下载地址
2. 创建一个新的Spring Boot项目
- 打开IntelliJ IDEA,选择“Create New Project”。
- 在左侧选择“Spring”选项。
- 选择适合的Spring Boot版本(推荐使用最新稳定版本)。
- 配置项目 metadata,例如:
-
Project name
: 输入你的项目名称,例如spring_boot_demo
。 -
Project location
: 选择一个存储路径。 -
Java SDK
: 确保选择了JDK 17或更高版本。注意勾选如下红色标识框所示选项: -
-
Spring Boot
: 选择一个适合的版本,例如3.4.2
。 -
Template
: 选择 “Web” 和 “MyBatis Spring Boot Starter”。勾选如下3个依赖项: -
-
Project metadata
: 配置Group
和Artifact
,例如:- Group:
com.example
- Artifact:
spring_boot_demo
- Group:
- 点击“Finish”创建项目。
3. 配置MySQL数据库
3.1 安装MySQL
- 下载并安装MySQL Community Server:
- MySQL 官方下载地址
- 安装完成后,启动MySQL服务。
3.2 创建数据库和表
打开MySQL命令行工具(或使用heidisql、TablePlus等可视化工具)并执行以下SQL语句:
-- 创建数据库
CREATE DATABASE demo_db;
-- 切换到数据库
USE demo_db;
-- 创建表
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
age INT
);
3.3 插入测试数据
-- 插入测试数据
INSERT INTO users (name, email, age)
VALUES
('张三', 'zhangsan@example.com', 25),
('李四', 'lisi@example.com', 30),
('王五', 'wangwu@example.com', 28);
4. 配置MySQL连接
在项目的 application.properties
文件中,添加以下配置:
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password # 输入你的MySQL密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis 配置
mybatis.type-aliases-package=com.example.spring_boot_demo.entity
mybatis.mapper-locations=classpath:mapper/*.xml
5. 创建实体类
创建一个 User
实体类,位于 src/main/java/com/example/spring_boot_demo/entity
目录:
package com.example.spring_boot_demo.entity;
public class User {
private Integer id;
private String name;
private String email;
private Integer age;
// 无参构造方法(必须)
public User() {}
// Getter 和 Setter 方法(必须)
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
}
6. 创建Mapper接口
在 src/main/java/com/example/spring_boot_demo/mapper
目录下,创建一个 UserMapper
接口:
package com.example.spring_boot_demo.mapper;
import com.example.spring_boot_demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users")
List<User> findAll();
}
7. 实现服务层
在 src/main/java/com/example/spring_boot_demo/service
目录下,创建一个 UserService
类:
package com.example.spring_boot_demo.service;
import com.example.spring_boot_demo.entity.User;
import com.example.spring_boot_demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserMapper userMapper;
@Autowired
public UserService(UserMapper userMapper) {
this.userMapper = userMapper;
}
public List<User> getAllUsers() {
return userMapper.findAll();
}
}
8. 创建控制层
在 src/main/java/com/example/spring_boot_demo/controller
目录下,创建一个 UserController
类:
package com.example.spring_boot_demo.controller;
import com.example.spring_boot_demo.entity.User;
import com.example.spring_boot_demo.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.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
代码解释
这个代码片段是一个基于Spring Boot的RESTful API控制器,用于处理与用户相关的HTTP请求。下面是对代码的详细解释:
1)包声明
package com.example.spring_boot_demo.controller;
- 这行代码声明了当前类所在的包路径。包路径通常用于组织和管理代码,确保类名的唯一性。
2) 导入依赖
import com.example.spring_boot_demo.entity.User;
import com.example.spring_boot_demo.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.RestController;
import java.util.List;
- 这些
import
语句导入了代码中所需的类。包括:User
:用户实体类,通常用于表示数据库中的用户表。UserService
:服务层接口或类,用于处理业务逻辑。- Spring框架的注解:如
@Autowired
、@GetMapping
、@RequestMapping
、@RestController
等。 List
:Java集合框架中的接口,用于存储一组对象。
3)控制器类
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
-
@RestController
:这个注解表示该类是一个RESTful风格的控制器。它结合了@Controller
和@ResponseBody
注解,意味着该类中的方法返回的数据将直接作为HTTP响应体返回,而不是视图名称。 -
@RequestMapping("/users")
:这个注解用于映射HTTP请求到控制器的处理方法。在这里,所有以/users
开头的请求都会由UserController
处理。 -
private final UserService userService;
:这是一个私有的、不可变的UserService
类型的成员变量。final
关键字表示这个变量一旦被初始化后就不能再被修改。 -
@Autowired
:这个注解用于自动注入依赖。Spring框架会自动查找合适的UserService
实现类,并将其注入到UserController
中。这里使用了构造函数注入的方式。 -
public UserController(UserService userService)
:这是控制器的构造函数,用于初始化userService
。由于使用了@Autowired
注解,Spring会自动将UserService
的实例传递给这个构造函数。 -
@GetMapping
:这个注解用于映射HTTP GET请求到getAllUsers
方法。当客户端发送一个GET请求到/users
时,这个方法会被调用。 -
public List<User> getAllUsers()
:这是控制器中的一个方法,用于处理GET请求。它调用userService.getAllUsers()
方法来获取所有用户的数据,并返回一个List<User>
对象。这个列表会被自动转换为JSON格式并作为HTTP响应体返回给客户端。
4) 总结
- 这个
UserController
类是一个典型的Spring Boot RESTful控制器,它通过UserService
来处理与用户相关的业务逻辑,并通过HTTP接口暴露这些功能。 - 当客户端发送一个GET请求到
/users
时,控制器会调用userService.getAllUsers()
方法,获取所有用户的数据,并将其以JSON格式返回给客户端。 - 这种设计遵循了MVC(Model-View-Controller)模式,控制器负责处理请求和响应,服务层负责业务逻辑,实体类负责数据模型。
9. 启动Spring Boot应用
- 打开项目的主类
SpringBootDemoApplication.java
并运行:
package com.example.spring_boot_demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}
- 应用启动后,控制台会显示:
浏览器输入:http://localhost:8080/users获取如下
10. 使用Postman测试API
- 打开Postman,发送一个
GET
请求到以下地址:http://localhost:8080/users
- 如果配置无误,你将收到如下JSON响应:
[ { "id": 1, "name": "张三", "email": "zhangsan@example.com", "age": 25 }, { "id": 2, "name": "李四", "email": "lisi@example.com", "age": 30 }, { "id": 3, "name": "王五", "email": "wangwu@example.com", "age": 28 } ]
11. 在IntelliJ IDEA中使用数据库工具
IntelliJ IDEA 提供了强大的数据库工具,能帮助你直接在IDE中管理数据库。
- 打开数据库工具:
- 点击菜单栏的 “View > Tool Windows > Database”
- 配置数据源:
- 点击 “+” 按钮并选择 “MySQL”
- 输入主机、端口、数据库名、用户名和密码
- 操作数据库:
- 你可以直接在IDE中执行SQL语句、查看表结构等。
注意事项
- 数据库密码:
- 确保
application.properties
中的数据库密码与MySQL安装时设置的密码一致。
- 确保
- 端口占用:
- 如果提示 “Port 8080 is already in use”,检查是否有其他应用占用了该端口。
- 字段匹配:
- 确保数据库表字段与
User
类中的字段保持一致。
- 确保数据库表字段与
- MyBatis日志:
- 如果需要调试MyBatis SQL,可以启用日志:
logging.level.com.example.spring_boot_demo.mapper=DEBUG
- 如果需要调试MyBatis SQL,可以启用日志:
总结
通过以上步骤,你已经成功使用IntelliJ IDEA 2024.2.3开发了一个基于Spring Boot、MyBatis和MySQL的Web应用。你可以通过扩展控制器和Mapper接口,添加更多功能,如添加、修改和删除用户数据。希望本文能帮助你快速上手这些技术栈的开发!