Springboot + JSP + Spring Security:配置資料來源失敗。如何配置 MySQL 中的資料來源?
若要在 Springboot 中配置資料來源,可以將資料來源定義到 **application.properties** 中。
Springboot 中的 application.properties 如下所示 −
spring.datasource.username=yourUserName spring.datasource.password=yourPassword spring.datasource.url=yourDatabaseUrl spring.datasource.driver-class-name=yourDriverClassName
專案結構如下 −

示例
為了理解上述概念,讓我們用 Spring Boot 建立一個控制器類。Java 程式碼如下所示 −
package com.demo.controller;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class DisplayController {
@Autowired
EntityManager entityManager;
@GetMapping("/getdata")
public String getAll() {
Query data= entityManager.createNativeQuery("select first_name from demo25");
List<String> allData= data.getResultList();
return allData.toString();
}
}示例
以下是 Java Spring Boot 的主類 −
package com.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class JavaMysqlDemoApplication {
public static void main(String[] args) {
SpringApplication.run(JavaMysqlDemoApplication.class, args);
}
}這是實際的 Spring Boot application.properties。

若要執行上述專案,請右鍵單擊主類 − 使用“作為 Java 應用程式執行”。若要獲取輸出,可以使用以下 URL −
https://:yourPortNumber/users/getdata
這將生成以下輸出 −

以下是在上文輸出中出現的表。
讓我們建立一個表 −
mysql> create table demo25 −> ( −> first_name varchar(20) −> ); Query OK, 0 rows affected (0.72 sec)
藉助 insert 命令向表中插入一些記錄 −
mysql> insert into demo25 values('David');
Query OK, 1 row affected (0.10 sec)
mysql> insert into demo25 values('Adam');
Query OK, 1 row affected (0.13 sec)
mysql> insert into demo25 values('Chris');
Query OK, 1 row affected (0.10 sec)使用 select 語句從表中顯示記錄 −
mysql> select *from demo25;
這將生成以下輸出 −
+------------+ | first_name | +------------+ | David | | Adam | | Chris | +------------+ 3 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP