Spring Boot 初级入门教程(十四) —— 配置 MySQL 数据库和使用 JdbcTemplate 测试

版权声明:本文为博主原创文章,转载请注明文章链接。 https://blog.csdn.net/tzhuwb/article/details/82724675

经过前面几篇文章,包已经可以打了,不管是 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 测试已完成。

猜你喜欢

转载自blog.csdn.net/tzhuwb/article/details/82724675