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
项目结构如下:
阅读更多:MySQL 教程
示例
为了理解上述概念,让我们使用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:
http://localhost: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)