Spring Boot 初级入门教程(十六) —— 配置 Oracle 数据库和使用 MyBatis 测试

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

日常项目开发除了 MySQL 数据库之外,用的最多的还有 Oracle 数据库,所以这边来说说如何在项目中配置 Oracle 数据库,并测试是否配置成功。

一、引入依赖的 jar 包

查看 pom.xml 文件中是否引入了 ojdbc 的 jar 包,如果没有引用,则需要引用才行。

		<!-- oracle jdbc 插件 -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc14</artifactId>
			<version>10.2.0.1.0</version>
		</dependency>

二、配置 oracle 连接信息

修改 application.properties 配置文件,配置 oracle 连接信息,配置如下:

#################################
## Oracle 数据库配置
#################################
# Oracle数据库连接
spring.datasource.url=jdbc:oracle:thin:@192.168.220.240:1521:orcl
# Oracle数据库用户名
spring.datasource.username=scott
# Oracle数据库密码
spring.datasource.password=123456
# Oracle数据库驱动(该配置可以不用配置,因为Spring Boot可以从url中为大多数数据库推断出它)
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1 FROM DUAL
spring.datasource.test-on-borrow=true
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=10000)

三、启动 Oracle 数据库并建表

这一步,自行操作,需要启动 Oracle 数据库,并建表 user_info,添加测试数据。

四、添加测试 Controller 类

OracleController.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 Oracle数据库控制类
 *
 * @author 孟郎郎
 * @blog http://blog.csdn.net/tzhuwb
 * @version 1.0
 * @date 2018年10月17日下午4:39:36
 */
@RestController
@RequestMapping("/oracledb")
public class OracleController {

	@Autowired
	private JdbcTemplate jdbcTemplate;

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

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

		return list;
	}

}

五、启动项目并测试

启动项目,浏览器输入http://localhost:8080/oracledb/getUsers,结果如下:

到此,连接 Oracle 数据库并用 JdbcTemplate 测试已完成。

猜你喜欢

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