文本將對在spring Boot構建的Web應用中,基于MySQL數據庫的幾種數據庫連接方式進行介紹。
包括JDBC、JPA、MyBatis、多數據源和事務。
JDBC 連接數據庫
1、屬性配置文件(application.properties)
1
2
3
4
|
spring.datasource.url=jdbc:mysql: //localhost:3306/test spring.datasource.username=root spring.datasource.password= 123456 spring.datasource.driver- class -name=com.mysql.jdbc.Driver |
如果使用JNDI,則可以替代 spring.datasource 的 url、username、password,如:
1
|
spring.datasource.jndi-name=java:tomcat/datasources/example |
值得一提的是,無論是Spring Boot默認的DataSource配置還是你自己的DataSource bean,都會引用到外部屬性文件中的屬性配置。所以假設你自定義的DataSource bean,你可以在定義bean時設置屬性,也可以在屬性文件中,以“spring.datasource.*”的方式使屬性配置外部化。
2、pom.xml 配置maven依賴
1
2
3
4
5
6
7
8
9
10
|
<!-- MYSQL --> < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > </ dependency > <!-- Spring Boot JDBC --> < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-jdbc</ artifactId > </ dependency > |
3、Java代碼范例
StudentService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package org.springboot.sample.service; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springboot.sample.entity.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; /** * Studeng Service * * @author 單紅宇(365384722) * @create 2016年1月12日 */ @Service public class StudentService { @Autowired private JdbcTemplate jdbcTemplate; public List<Student> getList(){ String sql = "SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT" ; return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){ @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { Student stu = new Student(); stu.setId(rs.getInt( "ID" )); stu.setAge(rs.getInt( "AGE" )); stu.setName(rs.getString( "NAME" )); stu.setSumScore(rs.getString( "SCORE_SUM" )); stu.setAvgScore(rs.getString( "SCORE_AVG" )); return stu; } }); } } |
Student.java 實體類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package org.springboot.sample.entity; import java.io.Serializable; /** * 學生實體 * * @author 單紅宇(365384722) * @create 2016年1月12日 */ public class Student implements Serializable{ private static final long serialVersionUID = 2120869894112984147L; private int id; private String name; private String sumScore; private String avgScore; private int age; // 節省文章長度,get set 方法省略 } |
StudentController.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package org.springboot.sample.controller; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springboot.sample.entity.Student; import org.springboot.sample.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping ( "/stu" ) public class StudentController { private static final Logger logger = LoggerFactory.getLogger(StudentController. class ); @Autowired private StudentService studentService; @RequestMapping ( "/list" ) public List<Student> getStus(){ logger.info( "從數據庫讀取Student集合" ); return studentService.getList(); } } |
本文對工程添加文件后工程結構圖:
然后啟動項目,訪問地址: http://localhost:8080/myspringboot/stu/list 響應結果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
[ { id: 1, name: "小明" , sumScore: "252" , avgScore: "84" , age: 1 }, { id: 2, name: "小王" , sumScore: "187" , avgScore: "62.3" , age: 1 }, { id: 3, name: "莉莉" , sumScore: "" , avgScore: "" , age: 0 }, { id: 4, name: "柱子" , sumScore: "230" , avgScore: "76.7" , age: 1 }, { id: 5, name: "大毛" , sumScore: "" , avgScore: "" , age: 0 }, { id: 6, name: "亮子" , sumScore: "0" , avgScore: "0" , age: 1 } ] |
連接池說明
Tomcat7之前,Tomcat本質應用了DBCP連接池技術來實現的JDBC數據源,但在Tomcat7之后,Tomcat提供了新的JDBC連接池方案,作為DBCP的替換或備選方案,解決了許多之前使用DBCP的不利之處,并提高了性能。
Spring Boot為我們準備了最佳的數據庫連接池方案,只需要在屬性文件(例如application.properties)中配置需要的連接池參數即可。
我們使用Tomcat數據源連接池,需要依賴tomcat-jdbc,只要應用中添加了spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa依賴,則無需擔心這點,因為將會自動添加 tomcat-jdbc 依賴。
假如我們想用其他方式的連接池技術,只要配置自己的DataSource bean,即可覆蓋Spring Boot的自動配置。
請看我的數據源配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
spring.datasource.url=jdbc:mysql: //localhost:3306/test spring.datasource.username=root spring.datasource.password= 123456 spring.datasource.driver- class -name=com.mysql.jdbc.Driver 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 spring.datasource.test-on-borrow= false spring.datasource.test- while -idle= true spring.datasource.time-between-eviction-runs-millis= 18800 spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold= 0 ) |
配置過連接池的開發人員對這些屬性的意義都有所認識。
我們打開DEBUG日志輸出,logback.xml 中添加:
1
|
< logger name = "org.springframework.boot" level = "DEBUG" /> |
然后啟動項目,注意觀察日志輸出,如下圖中會顯示自動啟用了連接池:
我在上面的數據源配置中添加了過濾器,并設置了延遲時間為0(故意設置很低,實際項目中請修改):
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
這個時候,我們訪問 http://localhost:8080/myspringboot/stu/list 觀察日志,會發現框架自動將大于該時間的數據查詢進行警告輸出,如下:
2016-01-12 23:27:06.710 WARN 17644 --- [nio-8080-exec-1] o.a.t.j.p.interceptor.SlowQueryReport : Slow Query Report SQL=SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT; time=3 ms;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/catoop/article/details/50507516