亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot數(shù)據(jù)訪問的實(shí)現(xiàn)

 更新時(shí)間:2023年11月27日 10:26:56   作者:程序猿進(jìn)階  
本文主要介紹了SpringBoot數(shù)據(jù)訪問的實(shí)現(xiàn),引入各種xxxTemplate,xxxRepository來簡(jiǎn)化我們對(duì)數(shù)據(jù)訪問層的操作,感興趣的可以了解一下

對(duì)于數(shù)據(jù)訪問層,無論是SQL還是NoSQL,SpringBoot默認(rèn)采用整合Spring Data的方式進(jìn)行統(tǒng)一處理,添加大量自動(dòng)配置,屏蔽了很多設(shè)置。引入各種xxxTemplatexxxRepository來簡(jiǎn)化我們對(duì)數(shù)據(jù)訪問層的操作。對(duì)我們來說只需要進(jìn)行簡(jiǎ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】測(cè)試:默認(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ù)源:DataSourceHikariDataSource、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ù)庫(kù)。

@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、mysqljdbc模塊的starts;在pom.xml中會(huì)發(fā)現(xiàn)mybatisspringboot的整合依賴:這個(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è)MybatisMapper類,通過增刪改查注解@Select @Update @Insert @Delete對(duì)數(shù)據(jù)表進(jìn)行操作;

//指定這是一個(gè)操作數(shù)據(jù)庫(kù)的 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)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論