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

Spring Boot 初級入門教程(十六) —— 配置 Oracle 資料庫和使用 MyBatis 測試

日常專案開發除了 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 測試已完成。