Spring Boot 配置 MySQL 数据库连接 - 详细教程

本文将详细介绍如何在 Spring Boot 项目中配置 MySQL 数据库连接,包括添加驱动、配置数据源、配置 JPA 和测试连接等步骤。

1. 添加 MySQL 驱动

pom.xml 文件中添加以下依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>

2. 配置数据源

application.propertiesapplication.yml 文件中添加以下配置:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=password

其中,db_name 是你要连接的数据库名称,root 是 MySQL 的用户名,password 是 MySQL 的密码。

3. 配置 JPA

如果你要使用 JPA 来操作数据库,需要在 application.propertiesapplication.yml 文件中添加以下配置:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update

其中,hibernate.dialect 是指定使用的数据库类型,show-sql 是是否显示 SQL 语句,ddl-auto 是指定数据库的操作方式,update 表示每次启动应用程序时自动更新数据库结构。

4. 测试连接

可以创建一个简单的 Controller 来测试连接是否成功,例如:

@RestController
public class HelloController {
    
    @Autowired
    private DataSource dataSource;
    
    @GetMapping("/hello")
    public String hello() {
        try {
            Connection connection = dataSource.getConnection();
            return '连接成功!';
        } catch (SQLException e) {
            e.printStackTrace();
            return '连接失败!';
        }
    }
}

启动应用程序后,访问 http://localhost:8080/hello,如果返回“连接成功!”则说明连接成功。

SpringBoot 配置 MySQL 数据库连接 - 详细教程

原文地址: https://www.cveoy.top/t/topic/mzTn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录