Spring Boot JDBC 連接數(shù)據(jù)庫(kù)示例
文本將對(duì)在spring Boot構(gòu)建的Web應(yīng)用中,基于MySQL數(shù)據(jù)庫(kù)的幾種數(shù)據(jù)庫(kù)連接方式進(jìn)行介紹。
包括JDBC、JPA、MyBatis、多數(shù)據(jù)源和事務(wù)。
JDBC 連接數(shù)據(jù)庫(kù)
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é)省文章長(zhǎng)度,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ù)庫(kù)讀取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ù)庫(kù)連接池方案,只需要在屬性文件(例如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;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java使用JDBC連接數(shù)據(jù)庫(kù)的五種方式(IDEA版)
- Java 如何使用JDBC連接數(shù)據(jù)庫(kù)
- Java連接數(shù)據(jù)庫(kù)JDBC技術(shù)之prepareStatement的詳細(xì)介紹
- spring通過jdbc連接數(shù)據(jù)庫(kù)
- JDBC利用C3P0數(shù)據(jù)庫(kù)連接池連接數(shù)據(jù)庫(kù)
- Java實(shí)現(xiàn)JDBC連接數(shù)據(jù)庫(kù)簡(jiǎn)單案例
- java使用jdbc連接數(shù)據(jù)庫(kù)簡(jiǎn)單實(shí)例
- Java基于JDBC連接數(shù)據(jù)庫(kù)及顯示數(shù)據(jù)操作示例
- Spring的連接數(shù)據(jù)庫(kù)以及JDBC模板(實(shí)例講解)
- Java中JDBC連接數(shù)據(jù)庫(kù)詳解
- java 中JDBC連接數(shù)據(jù)庫(kù)代碼和步驟詳解及實(shí)例代碼
- Java編程中使用JDBC API連接數(shù)據(jù)庫(kù)和創(chuàng)建程序的方法
- java開發(fā)中基于JDBC連接數(shù)據(jù)庫(kù)實(shí)例總結(jié)
- Java基礎(chǔ)之JDBC的數(shù)據(jù)庫(kù)連接與基本操作
相關(guān)文章
SpringBoot項(xiàng)目中Maven剔除無用Jar引用的最佳實(shí)踐
在?Spring?Boot?項(xiàng)目開發(fā)中,Maven?是最常用的構(gòu)建工具之一,通過?Maven,我們可以輕松地管理項(xiàng)目所需的依賴,而,隨著項(xiàng)目的復(fù)雜化,無用的?Jar?包引用可能會(huì)逐漸增多,本文旨在詳細(xì)解析如何在?Spring?Boot?項(xiàng)目中剔除無用的?Jar?引用,需要的朋友可以參考下2025-01-01
Java Web stmp發(fā)送帶附件郵件(附SSL版)
這篇文章主要為大家詳細(xì)介紹了Java Web stmp發(fā)送帶附件郵件,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
springboot數(shù)據(jù)庫(kù)操作圖文教程
本文以圖文并茂的形式給大家介紹了springboot數(shù)據(jù)庫(kù)操作,感興趣的朋友一起看看吧2017-07-07
使用MapStruct進(jìn)行Java Bean映射的方式
MapStruct是一個(gè)用于JavaBean映射的注解處理器,它通過注解生成類型安全且性能優(yōu)異的映射代碼,避免手動(dòng)編寫重復(fù)的樣板代碼,主要特性包括類型安全、高性能、簡(jiǎn)潔和可定制性,使用步驟包括定義映射接口、創(chuàng)建源類和目標(biāo)類、生成映射代碼并調(diào)用映射方法2025-02-02

