在 Spring Boot 中连接 MySQL 数据库是一个常见的任务。Spring Boot 提供了自动配置功能,使得连接 MySQL 数据库变得非常简单。以下是详细的步骤:

一、添加依赖

首先,确保你的pom.xml文件中包含了 Spring Boot 的 Starter Data JPA 和 MySQL 驱动依赖。

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

    <!-- MySQL Driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

二、配置数据库连接

application.propertiesapplication.yml文件中配置数据库连接信息。

1.使用application.properties

# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
spring.datasource.username=your_username
spring.datasource.password=your_password

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

2.使用application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
    username: your_username
    password: your_password
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    properties:
      hibernate:
        format_sql: true

三、创建实体类

创建一个实体类来映射数据库表。例如,创建一个User实体类:

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long 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;
    }
}

四、创建仓库接口

创建一个仓库接口来操作数据库。Spring Data JPA 会自动实现这个接口。

package com.example.demo.repository;

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

public interface UserRepository extends JpaRepository<User, Long> {
}

五、创建服务类

创建一个服务类来处理业务逻辑。

package com.example.demo.service;

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

import java.util.List;

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

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

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

    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}

六、创建控制器

创建一个控制器来处理 HTTP 请求。

package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.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
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

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

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

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

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

七、运行应用程序

确保你的 MySQL 数据库正在运行,并且已经创建了相应的数据库和表。然后运行你的 Spring Boot 应用程序。

mvn spring-boot:run

八、测试 API

使用 Postman 或其他工具测试你的 API。例如:

• 获取所有用户:

• GEThttp://localhost:8080/users

• 获取单个用户:

• GEThttp://localhost:8080/users/{id}

• 创建用户:

• POSThttp://localhost:8080/users

• Body:

    {
      "name": "John Doe",
      "email": "john.doe@example.com"
    }
    ```


• 更新用户:

• PUT`http://localhost:8080/users/{id}`

• Body:

```json
    {
      "name": "Jane Doe",
      "email": "jane.doe@example.com"
    }

• 删除用户:

• DELETEhttp://localhost:8080/users/{id}

九、常见问题

1.数据库连接失败

• 确保 MySQL 服务正在运行。

• 检查application.propertiesapplication.yml文件中的数据库连接信息是否正确。

• 确保 MySQL 用户具有访问数据库的权限。

2.数据库表未自动创建

• 确保spring.jpa.hibernate.ddl-auto配置正确。例如,update会自动创建表,create会删除现有表并重新创建。

• 确保实体类的注解正确。

十、总结

通过上述步骤,你可以在 Spring Boot 中成功连接并操作 MySQL 数据库。Spring Boot 的自动配置功能使得连接数据库变得非常简单,你只需要添加必要的依赖、配置数据库连接信息、创建实体类、仓库接口和服务类,即可实现对数据库的操作。

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐