1. 程式人生 > 其它 >Springcloud 學習筆記04-Springboot連線資料庫

Springcloud 學習筆記04-Springboot連線資料庫

一、開啟user-service微服務

啟動類右鍵Run’UserServiceApplication’或者點選右上方啟動

2 Springboot連線Mysql資料庫

(1)首先我們將需要的包匯入,這幾個包都是我們稍後要用到的:

       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version
> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</
groupId> <artifactId>spring-beans</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <
version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency>

(2)在application.yml配置你資料庫的資訊

主要是在spring下新增datasource

server:
  port: 8201
spring:
  application:
    name: user-service
  datasource:
      url: jdbc:mysql://localhost:3306/day1?serverTimezone=UTC&useSSL=false
      username: root
      password: ******
      driver-class-name: com.mysql.cj.jdbc.Driver
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:10086/eureka/

(3)測試是否成功

建立一個controller包,在它下面建立一個TestController類

package com.hztest.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
public class TestController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/getUsers")
    public List<Map<String, Object>> getDbType(){
        String sql = "select * from student";
        List<Map<String, Object>> list =  jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : list) {
            Set<Map.Entry<String, Object>> entries = map.entrySet( );
            if(entries != null) {
                Iterator<Map.Entry<String, Object>> iterator = entries.iterator( );
                while(iterator.hasNext( )) {
                    Map.Entry<String, Object> entry =(Map.Entry<String, Object>) iterator.next( );
                    Object key = entry.getKey( );
                    Object value = entry.getValue();
                    System.out.println(key+":"+value);
                }
            }
        }
        return list;
    }

}

然後我們在瀏覽器端輸入:
http://localhost:埠號+路徑
http://localhost:8201/getUsers