1. 程式人生 > 其它 >SpringBoot整合MySql

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);
        }
    }

}

執行結果