SpringBoot數(shù)據(jù)訪問的實(shí)現(xiàn)
對(duì)于數(shù)據(jù)訪問層,無論是SQL還是NoSQL,SpringBoot默認(rèn)采用整合Spring Data的方式進(jìn)行統(tǒng)一處理,添加大量自動(dòng)配置,屏蔽了很多設(shè)置。引入各種xxxTemplate,xxxRepository來簡化我們對(duì)數(shù)據(jù)訪問層的操作。對(duì)我們來說只需要進(jìn)行簡單的設(shè)置即可。
一、整合基本的 JDBC 與數(shù)據(jù)源
【1】引入jdbc starter [spring-boot-starter-jdbc] 和MySQL驅(qū)動(dòng)。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
【2】在application.yml中配置數(shù)據(jù)源相關(guān)信息:
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://127.0.0.1:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
【3】測試:默認(rèn)使用的是org.apache.tomcat.jdbc.pool.DataSource作為數(shù)據(jù)源。數(shù)據(jù)源的相關(guān)配置都在DataSourceProperties里面。自動(dòng)配置原理:org.springframework.boot.autoconfigure.jdbc包中的DataSourceConfiguration,根據(jù)配置創(chuàng)建數(shù)據(jù)源,默認(rèn)使用Tomcat連接池;可以通過spring.datasource.type指定自定義數(shù)據(jù)源類型;SpringBoot默認(rèn)支持一下數(shù)據(jù)源:DataSource、HikariDataSource、BasicDataSource。用戶也可以自定義數(shù)據(jù)源:如下可知是通過build創(chuàng)建數(shù)據(jù)源的。利用反射創(chuàng)建type類型的數(shù)據(jù)源,并綁定相關(guān)屬性。
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
//通過 build 創(chuàng)建數(shù)據(jù)源的。利用反射創(chuàng)建 type 類型的數(shù)據(jù)源,并綁定相關(guān)屬性。
@Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}
}
【4】第二個(gè)比較重要的類DataSourceAutoConfiguration自動(dòng)配置類中的dataSourceInitializer繼承了ApplicationListener。
public class DataSourceAutoConfiguration {
private static final Log logger = LogFactory.getLog(DataSourceAutoConfiguration.class);
public DataSourceAutoConfiguration() {
}
@Bean
@ConditionalOnMissingBean
public DataSourceInitializer dataSourceInitializer(DataSourceProperties properties, ApplicationContext applicationContext) {
return new DataSourceInitializer(properties, applicationContext);
}
//......
}
class DataSourceInitializer implements ApplicationListener<DataSourceInitializedEvent> {
//......
}
DataSourceInitializer的兩個(gè)主要作用:①、運(yùn)行建表語句;②、運(yùn)行操作數(shù)據(jù)的sql語句;
//運(yùn)行建表語句
private void runSchemaScripts() {
List<Resource> scripts = this.getScripts("spring.datasource.schema", this.properties.getSchema(), "schema");
if(!scripts.isEmpty()) {
String username = this.properties.getSchemaUsername();
String password = this.properties.getSchemaPassword();
this.runScripts(scripts, username, password);
try {
this.applicationContext.publishEvent(new DataSourceInitializedEvent(this.dataSource));
if(!this.initialized) {
this.runDataScripts();
this.initialized = true;
}
} catch (IllegalStateException var5) {
logger.warn("Could not send event to complete DataSource initialization (" + var5.getMessage() + ")");
}
}
}
//運(yùn)行操作數(shù)據(jù)的 sql語句
private void runDataScripts() {
List<Resource> scripts = this.getScripts("spring.datasource.data", this.properties.getData(), "data");
String username = this.properties.getDataUsername();
String password = this.properties.getDataPassword();
this.runScripts(scripts, username, password);
}
【5】進(jìn)行數(shù)據(jù)表創(chuàng)建時(shí),默認(rèn)只需要將文件命名為:schema-*.sql;進(jìn)行數(shù)據(jù)操作時(shí),默認(rèn)只需要將文件命令為:data-*.sql;如果自定義sql文件時(shí),可以在application.yml中通過如下方式指定sql文件位置:傳入的是一個(gè)list列表
spring:
datasource:
schema:
- classpath: student.sql
【6】JdbcTemplateAutoConfiguration自動(dòng)配置類給容器中注入了JdbcTemplate組件,幫組我們操作數(shù)據(jù)庫。
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class JdbcTemplateAutoConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean({JdbcOperations.class})
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(this.dataSource);
}
}
【7】高級(jí)配置:使用druid數(shù)據(jù)源,首先需要引入依賴:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
【8】在yml配置文件中加入Druid
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://127.0.0.1:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
二、整合 Mybatis 數(shù)據(jù)源(注解版)
【1】創(chuàng)建項(xiàng)目:選中web、mybatis、mysql和jdbc模塊的starts;在pom.xml中會(huì)發(fā)現(xiàn)mybatis與springboot的整合依賴:這個(gè)依賴并不是以spring-boot開始的,說明并不是spring提供的依賴,而是由第三方mybatis提供的依賴包;
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
【2】定義個(gè)接口類,用來操作目標(biāo)表的增刪改查:通過@Mapper表示該接口類是一個(gè)Mybatis的Mapper類,通過增刪改查注解@Select @Update @Insert @Delete對(duì)數(shù)據(jù)表進(jìn)行操作;
//指定這是一個(gè)操作數(shù)據(jù)庫的 mapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id=#{id}")
public Department getDeptById(Integer id);
}
【3】通過Controller層調(diào)用Server繼而調(diào)用Mapper對(duì)數(shù)據(jù)完成操作:
@Controller
public class DepartmentController {
@Autowired
private DepartmentMapper mapper;
@GetMapping("/dept/{id}")
public Department getDeptById(@PathVariable("id") Integer id){
return mapper.getDeptById(id);
}
}到此這篇關(guān)于SpringBoot數(shù)據(jù)訪問的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot數(shù)據(jù)訪問內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot對(duì)數(shù)據(jù)訪問層進(jìn)行單元測試的方法詳解
- 基于Springboot+Mybatis對(duì)數(shù)據(jù)訪問層進(jìn)行單元測試的方式分享
- springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解
- SpringBoot實(shí)戰(zhàn)記錄之?dāng)?shù)據(jù)訪問
- 深入了解Springboot核心知識(shí)點(diǎn)之?dāng)?shù)據(jù)訪問配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問的詳細(xì)過程
- SpringBoot數(shù)據(jù)訪問自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡單數(shù)據(jù)訪問應(yīng)用的實(shí)例代碼
相關(guān)文章
Maven多模塊項(xiàng)目調(diào)試與問題排查的完整指南
在現(xiàn)代企業(yè)級(jí)Java開發(fā)中,Maven多模塊項(xiàng)目因其清晰的代碼組織,依賴管理和高效的構(gòu)建流程已成為主流架構(gòu)模式,本文深入剖析多模塊項(xiàng)目的四大核心痛點(diǎn)解決方案,感興趣的小伙伴可以跟隨小編一起了解下2025-06-06
關(guān)于Idea使用git時(shí)commit特別慢的問題及解決方法
這篇文章主要介紹了關(guān)于Idea使用git時(shí)commit特別慢的問題及解決方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Java8之函數(shù)式接口及常用函數(shù)式接口講解
這篇文章主要介紹了Java8之函數(shù)式接口及常用函數(shù)式接口,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
IDEA中的yml文件與properties互相轉(zhuǎn)換
這篇文章主要介紹了IDEA中的yml文件與properties互相轉(zhuǎn)換方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
關(guān)于Idea的Invalidate Caches/Restart使用
Java調(diào)用Pytorch模型實(shí)現(xiàn)圖像識(shí)別
Java中InputStream流的多次讀取的實(shí)現(xiàn)示例
一個(gè)Java工程師超實(shí)用的17個(gè)日常效率工具

