1. 程式人生 > >Spring Boot 初級入門教程(十四) —— 配置 MySQL 資料庫和使用 JdbcTemplate 測試

Spring Boot 初級入門教程(十四) —— 配置 MySQL 資料庫和使用 JdbcTemplate 測試

經過前面幾篇文章,包已經可以打了,不管是 jar 包還是 war 包都已測試通過,jsp 頁面也可以訪問了,但頁面上的資料都是在配置檔案中寫死的,不爽 ~

到目前為止,最重要的配置還沒做,那就是連資料庫,這篇就主要說一下如何配置 MySQL 資料庫。

一、引入依賴的 jar 包

檢視 pom.xml 檔案中是否引入 spring-boot-starter-jdbc 和 mysql-connector-java 的 jar 包,如果沒有引用,則需要引用才行。

		<!-- 新增 jdbc 驅動依賴包 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
			<version>2.0.2.RELEASE</version>
		</dependency>

		<!-- mysql jdbc 外掛 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.46</version>
		</dependency>

二、配置 mysql 連線資訊

修改 application.properties 配置檔案,配置 mysql 連線資訊,配置如下:

#################################
## MySQL 資料庫配置
#################################
# MySQL資料庫連線
spring.datasource.url=jdbc:mysql://192.168.220.240:3306/test_springboot?characterEncoding=UTF-8
# MySQL資料庫使用者名稱
spring.datasource.username=root
# MySQL資料庫密碼
spring.datasource.password=123456
# MySQL資料庫驅動(該配置可以不用配置,因為Spring Boot可以從url中為大多數資料庫推斷出它)
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5

三、啟動 MySQL 資料庫並建表

這一步,自行操作,需要啟動 MySQL 資料庫,並建表 user,新增測試資料。

四、新增測試 Controller 類

MySQLController.java:

package com.menglanglang.test.springboot.controller;

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

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;

/**
 * @desc MySQL資料庫控制類
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年9月16日下午3:18:02
 */
@RestController
@RequestMapping("/mysqldb")
public class MySQLController {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@RequestMapping("/getUsers")
	public List<Map<String, Object>> getUser() {

		String sql = "select * from user";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);

		return list;
	}

}

五、啟動專案並測試

啟動專案,瀏覽器輸入http://localhost:8080/mysqldb/getUsers,結果如下:

到此,連線 MySQL 資料庫並用 JdbcTemplate 測試已完成。