SpringBoot整合MySql

SpringBoot整合MySql

系统要求

Java 8+

springBoot2.5 +

创建springBoot项目工程

导入依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
编写application.yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3307/webapp1
    username: webapp1
    password: webapp1
进行测试
package com.xiang.springbootdatabase;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

@SpringBootTest
class SpringBootDatabaseApplicationTests {
    /*该对象是SpringBoot创建的可以对数据进行操作*/
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Test
    /**
     * 查询所有
     */
    void contextLoads() {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from user;");
        for (Map<String, Object> map : list) {
            System.out.println(map);
        }
    }

}

运行结果

原文地址:https://www.cnblogs.com/d534/p/15417647.html