java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > IDEA SpringBoot接入MySQL数据库

IDEA中为SpringBoot项目接入MySQL数据库的详细指南

作者:一切皆有迹可循

MySQL作为最流行的开源关系型数据库,与Spring Boot的整合是企业级开发的标配,本文将手把手教你‌在IntelliJ IDEA中为Spring Boot项目接入MySQL数据库‌,有需要的可以了解下

‌前言

MySQL作为最流行的开源关系型数据库,与Spring Boot的整合是企业级开发的标配。本文将手把手教你‌在IntelliJ IDEA中为Spring Boot项目接入MySQL数据库‌,涵盖‌依赖配置‌、‌实体类映射‌、‌JPA操作‌及‌常见避坑指南‌,助你快速实现数据持久化!

‌一、环境准备

1. ‌基础环境

已安装IntelliJ IDEA并创建Spring Boot项目(参考文章)。

本地安装MySQL 5.7+(推荐8.0),并创建数据库(如springboot_db)。

2. ‌检查依赖

确保项目包含Spring Web、Spring Data JPA和MySQL Driver依赖(可通过pom.xml添加)。

‌二、添加MySQL依赖

修改pom.xml

在<dependencies>中添加以下依赖:

<!-- Spring Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- MySQL驱动(版本需与本地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>

‌注意‌:Spring Boot 3.x默认使用MySQL 8.x驱动,若使用MySQL 5.x需指定驱动版本(如5.1.49)。

‌三、配置MySQL连接

‌1. 修改application.properties

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

# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

‌关键参数解释‌:

‌2. 验证配置

启动项目,若控制台输出以下日志,说明数据库连接成功:

HikariPool-1 - Start completed

‌四、创建实体类与Repository

‌1. 定义实体类(User)

package com.example.demo.entity;

import jakarta.persistence.*;
import lombok.Data;

@Data
@Entity
@Table(name = "user") // 指定表名
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(nullable = false, unique = true)
    private String username;
    
    @Column(nullable = false)
    private String password;
    
    private String email;
}

‌注解说明‌:

‌2. 创建Repository接口

package com.example.demo.repository;

import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    // 自定义查询方法(按用户名查找)
    User findByUsername(String username);
}

五、编写Service与Controller

‌1. 实现Service层

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User saveUser(User user) {
        return userRepository.save(user);
    }

    public User findUserByUsername(String username) {
        return userRepository.findByUsername(username);
    }
}

‌2. 编写RESTful Controller

package com.example.demo.controller;

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

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

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

    @GetMapping("/{username}")
    public User getUser(@PathVariable String username) {
        return userService.findUserByUsername(username);
    }
}

‌六、测试与验证

‌1. 启动应用

运行启动类DemoApplication,观察控制台是否生成建表SQL:

create table user (
    id bigint not null auto_increment,
    email varchar(255),
    password varchar(255) not null,
    username varchar(255) not null unique,
    primary key (id)
);

‌2. 使用Postman测试API

‌新增用户‌(POST请求):URL:http://localhost:8080/api/users

Body(JSON):

{
  "username": "csdn_user",
  "password": "123456",
  "email": "csdn@example.com"
}

‌查询用户‌(GET请求):URL:http://localhost:8080/api/users/csdn_user

‌七、常见问题与解决方案

‌Q1:数据库连接失败(Access denied)

原因‌:用户名/密码错误,或用户无权限访问数据库。

‌解决‌:

检查application.properties中的username和password。

在MySQL中授权用户:

GRANT ALL PRIVILEGES ON springboot_db.* TO 'root'@'localhost';
FLUSH PRIVILEGES;

‌Q2:驱动类未找到(Driver class not found)

原因‌:MySQL驱动版本与配置不匹配。

‌解决‌:

检查spring.datasource.driver-class-name是否为com.mysql.cj.jdbc.Driver(MySQL 8.x)。

确认pom.xml中MySQL依赖未冲突。

Q3:时区错误(ServerTimezone not configured)

‌解决‌:在JDBC URL中添加&serverTimezone=Asia/Shanghai(或UTC)。

‌Q4:表不存在(Table ‘springboot_db.user’ doesn’t exist)

解决‌:

确保spring.jpa.hibernate.ddl-auto=update。

检查实体类@Table(name="user")是否与数据库表名一致。

总结

通过Spring Data JPA,开发者无需编写SQL即可实现MySQL数据库的CRUD操作。本文从配置到实战演示了完整的接入流程,并针对常见错误提供解决方案。

到此这篇关于IDEA中为SpringBoot项目接入MySQL数据库的详细指南的文章就介绍到这了,更多相关IDEA SpringBoot接入MySQL数据库内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文