Spring Boot JDBC 連接數(shù)據(jù)庫示例
文本將對(duì)在spring Boot構(gòu)建的Web應(yīng)用中,基于MySQL數(shù)據(jù)庫的幾種數(shù)據(jù)庫連接方式進(jìn)行介紹。
包括JDBC、JPA、MyBatis、多數(shù)據(jù)源和事務(wù)。
JDBC 連接數(shù)據(jù)庫
1、屬性配置文件(application.properties)
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,如:
spring.datasource.jndi-name=java:tomcat/datasources/example
值得一提的是,無論是Spring Boot默認(rèn)的DataSource配置還是你自己的DataSource bean,都會(huì)引用到外部屬性文件中的屬性配置。所以假設(shè)你自定義的DataSource bean,你可以在定義bean時(shí)設(shè)置屬性,也可以在屬性文件中,以“spring.datasource.*”的方式使屬性配置外部化。
2、pom.xml 配置maven依賴
<!-- 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
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 實(shí)體類
package org.springboot.sample.entity;
import java.io.Serializable;
/**
* 學(xué)生實(shí)體
*
* @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;
// 節(jié)省文章長度,get set 方法省略
}
StudentController.java
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("從數(shù)據(jù)庫讀取Student集合");
return studentService.getList();
}
}
本文對(duì)工程添加文件后工程結(jié)構(gòu)圖:

然后啟動(dòng)項(xiàng)目,訪問地址: http://localhost:8080/myspringboot/stu/list 響應(yīng)結(jié)果如下:
[
{
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本質(zhì)應(yīng)用了DBCP連接池技術(shù)來實(shí)現(xiàn)的JDBC數(shù)據(jù)源,但在Tomcat7之后,Tomcat提供了新的JDBC連接池方案,作為DBCP的替換或備選方案,解決了許多之前使用DBCP的不利之處,并提高了性能。
Spring Boot為我們準(zhǔn)備了最佳的數(shù)據(jù)庫連接池方案,只需要在屬性文件(例如application.properties)中配置需要的連接池參數(shù)即可。
我們使用Tomcat數(shù)據(jù)源連接池,需要依賴tomcat-jdbc,只要應(yīng)用中添加了spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa依賴,則無需擔(dān)心這點(diǎn),因?yàn)閷?huì)自動(dòng)添加 tomcat-jdbc 依賴。
假如我們想用其他方式的連接池技術(shù),只要配置自己的DataSource bean,即可覆蓋Spring Boot的自動(dòng)配置。
請(qǐng)看我的數(shù)據(jù)源配置:
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)
配置過連接池的開發(fā)人員對(duì)這些屬性的意義都有所認(rèn)識(shí)。
我們打開DEBUG日志輸出,logback.xml 中添加:
<logger name="org.springframework.boot" level="DEBUG"/>
然后啟動(dòng)項(xiàng)目,注意觀察日志輸出,如下圖中會(huì)顯示自動(dòng)啟用了連接池:
我在上面的數(shù)據(jù)源配置中添加了過濾器,并設(shè)置了延遲時(shí)間為0(故意設(shè)置很低,實(shí)際項(xiàng)目中請(qǐng)修改):
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
這個(gè)時(shí)候,我們?cè)L問 http://localhost:8080/myspringboot/stu/list 觀察日志,會(huì)發(fā)現(xiàn)框架自動(dòng)將大于該時(shí)間的數(shù)據(jù)查詢進(jìn)行警告輸出,如下:
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;
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java使用JDBC連接數(shù)據(jù)庫的五種方式(IDEA版)
- Java 如何使用JDBC連接數(shù)據(jù)庫
- Java連接數(shù)據(jù)庫JDBC技術(shù)之prepareStatement的詳細(xì)介紹
- spring通過jdbc連接數(shù)據(jù)庫
- JDBC利用C3P0數(shù)據(jù)庫連接池連接數(shù)據(jù)庫
- Java實(shí)現(xiàn)JDBC連接數(shù)據(jù)庫簡單案例
- java使用jdbc連接數(shù)據(jù)庫簡單實(shí)例
- Java基于JDBC連接數(shù)據(jù)庫及顯示數(shù)據(jù)操作示例
- Spring的連接數(shù)據(jù)庫以及JDBC模板(實(shí)例講解)
- Java中JDBC連接數(shù)據(jù)庫詳解
- java 中JDBC連接數(shù)據(jù)庫代碼和步驟詳解及實(shí)例代碼
- Java編程中使用JDBC API連接數(shù)據(jù)庫和創(chuàng)建程序的方法
- java開發(fā)中基于JDBC連接數(shù)據(jù)庫實(shí)例總結(jié)
- Java基礎(chǔ)之JDBC的數(shù)據(jù)庫連接與基本操作
相關(guān)文章
Java使用lambda自定義Arrays.sort排序規(guī)則說明
這篇文章主要介紹了Java使用lambda自定義Arrays.sort排序規(guī)則說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
spring boot 監(jiān)聽容器啟動(dòng)代碼實(shí)例
這篇文章主要介紹了spring boot 監(jiān)聽容器啟動(dòng)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
java實(shí)現(xiàn)上傳圖片進(jìn)行切割的方法
這篇文章主要介紹了java實(shí)現(xiàn)上傳圖片進(jìn)行切割的方法,以完整實(shí)例形式分析了Java針對(duì)上傳圖片進(jìn)行切割的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2015-02-02
mybatis和mybatis-plus同時(shí)使用的坑
本文主要介紹了mybatis和mybatis-plus同時(shí)使用的坑,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05
mybatis 自定義實(shí)現(xiàn)攔截器插件Interceptor示例
這篇文章主要介紹了mybatis 自定義實(shí)現(xiàn)攔截器插件Interceptor,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
SpringBoot整合Mybatis與MybatisPlus方法詳細(xì)講解
這篇文章主要介紹了SpringBoot整合Mybatis與MybatisPlus方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

