數(shù)據(jù)庫使用MySQL,我們先創(chuàng)建一個SpringBoot項目再導入MySQL驅(qū)動:
江口ssl適用于網(wǎng)站、小程序/APP、API接口等需要進行數(shù)據(jù)傳輸應用場景,ssl證書未來市場廣闊!成為創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場價格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:18980820575(備注:SSL證書合作)期待與您的合作!
org.springframework.boot
spring-boot-starter-jdbc
mysql
mysql-connector-java
runtime
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.137.140:3306/mysql
driver-class-name: com.mysql.jdbc.Driver
package cn.zhangyu;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import static sun.misc.Version.println;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
DataSourceInitializer:ApplicationListener;可以幫助我們執(zhí)行sql語句,但是需要將文件命名為:schema-.sql、data-.sql
默認規(guī)則:schema.sql,schema-all.sql;(DataSourceProperties這個類進行了默認的配置)
DataSourceInitializer作用:
1)、runSchemaScripts();運行建表語句;
2)、runDataScripts();運行插入數(shù)據(jù)的sql語句;
再pom中添加
# 如果你配置文件沒有指定執(zhí)行文件的名稱而是使用默認的schema.sql或者schema-all.sql的話
# 就在配置文件中加上spring.datasource.initialization-mode=always
initialization-mode: always
我們再resources目錄下放入schema.sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO department(id,departmentName) VALUES(1,'業(yè)務部');
INSERT INTO department(id,departmentName) VALUES(2,'前臺部');
查看結(jié)果
mysql> select * from department;
+----+----------------+
| id | departmentName |
+----+----------------+
| 1 | 業(yè)務部 |
| 2 | 前臺部 |
+----+----------------+
2 rows in set (0.00 sec)
---------------------
編寫controller 進行測試
package cn.zhangyu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* Created by grace on 2018/11/28.
*/
@RestController
public class HelloController {
//spring boot中已經(jīng)給我們注冊好JdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate;
@GetMapping("/hello")
public Map getDepartment(){
List
訪問http://localhost:8080/hello
:{"id":1,"departmentName":"業(yè)務部"}
#可以使用
schema:
- classpath:department.sql
schema是一個list所以可以使用-
指定多個位置