1. 添加MySQL驱动

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>
  1. 配置数据源

在application.properties或application.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的密码。

  1. 配置JPA

如果你要使用JPA来操作数据库,需要在application.properties或application.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表示每次启动应用程序时自动更新数据库结构。

  1. 测试连接

可以创建一个简单的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,如果返回“连接成功!”则说明连接成功。

java的springboot配置mysql

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

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