SpringBoot數(shù)據(jù)訪問的實(shí)現(xiàn)
對于數(shù)據(jù)訪問層,無論是SQL還是NoSQL,SpringBoot默認(rèn)采用整合Spring Data的方式進(jìn)行統(tǒng)一處理,添加大量自動(dòng)配置,屏蔽了很多設(shè)置。引入各種xxxTemplate,xxxRepository來簡化我們對數(shù)據(jù)訪問層的操作。對我們來說只需要進(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】高級配置:使用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中會發(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對數(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對數(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot對數(shù)據(jù)訪問層進(jìn)行單元測試的方法詳解
- 基于Springboot+Mybatis對數(shù)據(jù)訪問層進(jìn)行單元測試的方式分享
- springboot數(shù)據(jù)訪問和數(shù)據(jù)視圖的使用方式詳解
- SpringBoot實(shí)戰(zhàn)記錄之?dāng)?shù)據(jù)訪問
- 深入了解Springboot核心知識點(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)文章
Springmvc ViewResolver設(shè)計(jì)實(shí)現(xiàn)過程解析
這篇文章主要介紹了Springmvc ViewResolver設(shè)計(jì)實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
Java使用ant.jar執(zhí)行SQL腳本文件的示例代碼
這篇文章主要介紹了Java使用ant.jar執(zhí)行SQL腳本文件,文中通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2024-02-02
SpringBoot返回前端Long類型字段丟失精度問題及解決方案
Java服務(wù)端返回Long整型數(shù)據(jù)給前端,JS會自動(dòng)轉(zhuǎn)換為Number類型,本文主要介紹了SpringBoot返回前端Long類型字段丟失精度問題及解決方案,感興趣的可以了解一下2024-03-03
mybatis plus代碼生成工具的實(shí)現(xiàn)代碼
這篇文章主要介紹了mybatis plus代碼生成工具的實(shí)現(xiàn)代碼,需要的朋友可以參考下2021-04-04
java GUI實(shí)現(xiàn)學(xué)生圖書管理簡單實(shí)例
這篇文章主要為大家詳細(xì)介紹了java GUI實(shí)現(xiàn)學(xué)生圖書管理簡單示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
Java語言實(shí)現(xiàn)對MySql數(shù)據(jù)庫中數(shù)據(jù)的增刪改查操作的代碼
這篇文章主要介紹了Java語言實(shí)現(xiàn)對MySql數(shù)據(jù)庫中數(shù)據(jù)的增刪改查操作的代碼,實(shí)現(xiàn)了連接數(shù)據(jù)庫,和數(shù)據(jù)庫的增刪改查操作,有興趣的可以了解一下。2016-12-12
Spring Cloud動(dòng)態(tài)配置刷新@RefreshScope與@Component的深度解析
在現(xiàn)代微服務(wù)架構(gòu)中,動(dòng)態(tài)配置管理是一個(gè)關(guān)鍵需求,Spring Cloud 提供了 @RefreshScope 注解,允許應(yīng)用在運(yùn)行時(shí)動(dòng)態(tài)更新配置,而無需重啟服務(wù),本文深入探析Spring Cloud動(dòng)態(tài)配置刷新@RefreshScope與@Component,感興趣的朋友一起看看吧2025-04-04
SpringCloud Zuul在何種情況下使用Hystrix及問題小結(jié)
這篇文章主要介紹了SpringCloud Zuul在何種情況下使用Hystrix 及問題小結(jié),感興趣的朋友跟隨小編一起看看吧2018-11-11
java利用easyexcel實(shí)現(xiàn)導(dǎo)入與導(dǎo)出功能
這篇文章主要介紹了java利用easyexcel實(shí)現(xiàn)導(dǎo)入與導(dǎo)出功能,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下,希望對你的學(xué)習(xí)有所幫助2022-09-09
靈活控制任務(wù)執(zhí)行時(shí)間的Cron表達(dá)式范例
這篇文章主要為大家介紹了靈活控制任務(wù)執(zhí)行時(shí)間的Cron表達(dá)式范例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10

