SpringBoot數(shù)據(jù)訪問的實現(xiàn)
對于數(shù)據(jù)訪問層,無論是SQL還是NoSQL,SpringBoot默認采用整合Spring Data的方式進行統(tǒng)一處理,添加大量自動配置,屏蔽了很多設置。引入各種xxxTemplate,xxxRepository來簡化我們對數(shù)據(jù)訪問層的操作。對我們來說只需要進行簡單的設置即可。
一、整合基本的 JDBC 與數(shù)據(jù)源
【1】引入jdbc starter [spring-boot-starter-jdbc] 和MySQL驅(qū)動。
<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ù)源相關信息:
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://127.0.0.1:3306/jdbc
driver-class-name: com.mysql.jdbc.Driver
【3】測試:默認使用的是org.apache.tomcat.jdbc.pool.DataSource作為數(shù)據(jù)源。數(shù)據(jù)源的相關配置都在DataSourceProperties里面。自動配置原理:org.springframework.boot.autoconfigure.jdbc包中的DataSourceConfiguration,根據(jù)配置創(chuàng)建數(shù)據(jù)源,默認使用Tomcat連接池;可以通過spring.datasource.type指定自定義數(shù)據(jù)源類型;SpringBoot默認支持一下數(shù)據(jù)源:DataSource、HikariDataSource、BasicDataSource。用戶也可以自定義數(shù)據(jù)源:如下可知是通過build創(chuàng)建數(shù)據(jù)源的。利用反射創(chuàng)建type類型的數(shù)據(jù)源,并綁定相關屬性。
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
//通過 build 創(chuàng)建數(shù)據(jù)源的。利用反射創(chuàng)建 type 類型的數(shù)據(jù)源,并綁定相關屬性。
@Bean
public DataSource dataSource(DataSourceProperties properties) {
return properties.initializeDataSourceBuilder().build();
}
}
【4】第二個比較重要的類DataSourceAutoConfiguration自動配置類中的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的兩個主要作用:①、運行建表語句;②、運行操作數(shù)據(jù)的sql語句;
//運行建表語句
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() + ")");
}
}
}
//運行操作數(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】進行數(shù)據(jù)表創(chuàng)建時,默認只需要將文件命名為:schema-*.sql;進行數(shù)據(jù)操作時,默認只需要將文件命令為:data-*.sql;如果自定義sql文件時,可以在application.yml中通過如下方式指定sql文件位置:傳入的是一個list列表
spring:
datasource:
schema:
- classpath: student.sql
【6】JdbcTemplateAutoConfiguration自動配置類給容器中注入了JdbcTemplate組件,幫組我們操作數(shù)據(jù)庫。
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class JdbcTemplateAutoConfiguration {
@Bean
@Primary
@ConditionalOnMissingBean({JdbcOperations.class})
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(this.dataSource);
}
}
【7】高級配置:使用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)建項目:選中web、mybatis、mysql和jdbc模塊的starts;在pom.xml中會發(fā)現(xiàn)mybatis與springboot的整合依賴:這個依賴并不是以spring-boot開始的,說明并不是spring提供的依賴,而是由第三方mybatis提供的依賴包;
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
【2】定義個接口類,用來操作目標表的增刪改查:通過@Mapper表示該接口類是一個Mybatis的Mapper類,通過增刪改查注解@Select @Update @Insert @Delete對數(shù)據(jù)表進行操作;
//指定這是一個操作數(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對數(shù)據(jù)完成操作:
@Controller
public class DepartmentController {
@Autowired
private DepartmentMapper mapper;
@GetMapping("/dept/{id}")
public Department getDeptById(@PathVariable("id") Integer id){
return mapper.getDeptById(id);
}
}到此這篇關于SpringBoot數(shù)據(jù)訪問的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot數(shù)據(jù)訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringBoot對數(shù)據(jù)訪問層進行單元測試的方法詳解
- 基于Springboot+Mybatis對數(shù)據(jù)訪問層進行單元測試的方式分享
- springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解
- SpringBoot實戰(zhàn)記錄之數(shù)據(jù)訪問
- 深入了解Springboot核心知識點之數(shù)據(jù)訪問配置
- SpringBoot中Mybatis + Druid 數(shù)據(jù)訪問的詳細過程
- SpringBoot數(shù)據(jù)訪問自定義使用Druid數(shù)據(jù)源的方法
- SpringBoot+MyBatis簡單數(shù)據(jù)訪問應用的實例代碼
相關文章
Springmvc ViewResolver設計實現(xiàn)過程解析
這篇文章主要介紹了Springmvc ViewResolver設計實現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10
Java使用ant.jar執(zhí)行SQL腳本文件的示例代碼
這篇文章主要介紹了Java使用ant.jar執(zhí)行SQL腳本文件,文中通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-02-02
SpringBoot返回前端Long類型字段丟失精度問題及解決方案
Java服務端返回Long整型數(shù)據(jù)給前端,JS會自動轉(zhuǎn)換為Number類型,本文主要介紹了SpringBoot返回前端Long類型字段丟失精度問題及解決方案,感興趣的可以了解一下2024-03-03
Java語言實現(xiàn)對MySql數(shù)據(jù)庫中數(shù)據(jù)的增刪改查操作的代碼
這篇文章主要介紹了Java語言實現(xiàn)對MySql數(shù)據(jù)庫中數(shù)據(jù)的增刪改查操作的代碼,實現(xiàn)了連接數(shù)據(jù)庫,和數(shù)據(jù)庫的增刪改查操作,有興趣的可以了解一下。2016-12-12
Spring Cloud動態(tài)配置刷新@RefreshScope與@Component的深度解析
在現(xiàn)代微服務架構(gòu)中,動態(tài)配置管理是一個關鍵需求,Spring Cloud 提供了 @RefreshScope 注解,允許應用在運行時動態(tài)更新配置,而無需重啟服務,本文深入探析Spring Cloud動態(tài)配置刷新@RefreshScope與@Component,感興趣的朋友一起看看吧2025-04-04
SpringCloud Zuul在何種情況下使用Hystrix及問題小結(jié)
這篇文章主要介紹了SpringCloud Zuul在何種情況下使用Hystrix 及問題小結(jié),感興趣的朋友跟隨小編一起看看吧2018-11-11
java利用easyexcel實現(xiàn)導入與導出功能
這篇文章主要介紹了java利用easyexcel實現(xiàn)導入與導出功能,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下,希望對你的學習有所幫助2022-09-09

