小工具知识网

当前位置: 首页 > 行业知识 > SpringBoot——数据访问

行业知识

SpringBoot——数据访问

2026-11-01 13:41:57 来源:互联网转载

优质博文:IT-BLOG-CN

对于数据访问层,无论是 SQL 还是 NoSQL,SpringBoot 默认采用整合 Spring Data 的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种 xxxTemplate,xxxRepository 来简化我们对数据访问层的操作。对我们来说只需要进行简单的设置即可。

一、整合基本的 JDBC 与数据源

【1】引入 jdbc starter [spring-boot-starter-jdbc] 和 MySQL 驱动。

    org.springframework.boot    spring-boot-starter-data-jdbc    mysql    mysql-connector-java    runtime

【2】在 application.yml 中配置数据源相关信息:

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 作为数据源。数据源的相关配置都在 DataSourceProperties 里面。自动配置原理:org.springframework.boot.autoconfigure.jdbc 包中的 DataSourceConfiguration,根据配置创建数据源,默认使用 Tomcat 连接池;可以通过 spring.datasource.type 指定自定义数据源类型;SpringBoot 默认支持一下数据源:DataSource、HikariDataSource、BasicDataSource。用户也可以自定义数据源:如下可知是通过 build 创建数据源的。利用反射创建 type 类型的数据源,并绑定相关属性。

@ConditionalOnMissingBean({DataSource.class})@ConditionalOnProperty(    name = {"spring.datasource.type"})static class Generic {    Generic() {    }        //通过 build 创建数据源的。利用反射创建 type 类型的数据源,并绑定相关属性。    @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 {//......}

DataSourceInitializer 的两个主要作用:①、运行建表语句;②、运行操作数据的 sql语句;

//运行建表语句private void runSchemaScripts() {    List 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() + ")");        }    }}//运行操作数据的 sql语句private void runDataScripts() {    List 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】进行数据表创建时,默认只需要将文件命名为:schema-.sql;进行数据操作时,默认只需要将文件命令为:data-.sql;如果自定义sql 文件时,可以在 application.yml 中通过如下方式指定sql文件位置:传入的是一个 list 列表

spring:  datasource:    schema:      - classpath: student.sql

【6】JdbcTemplateAutoConfiguration 自动配置类给容器中注入了 JdbcTemplate 组件,帮组我们操作数据库。

@AutoConfigureAfter({DataSourceAutoConfiguration.class})public class JdbcTemplateAutoConfiguration {    @Bean    @Primary    @ConditionalOnMissingBean({JdbcOperations.class})    public JdbcTemplate jdbcTemplate() {        return new JdbcTemplate(this.dataSource);    }}

【7】高级配置:使用 druid 数据源,首先需要引入依赖:

    com.alibaba    druid    1.1.10

【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 数据源(注解版)

【1】创建项目:选中 web、mybatis、mysql 和 jdbc 模块的 starts;在 pom.xml 中会发现 mybatis 与 springboot 的整合依赖:这个依赖并不是以 spring-boot 开始的,说明并不是 spring 提供的依赖,而是由第三方 mybatis 提供的依赖包;

    org.mybatis.spring.boot    mybatis-spring-boot-starter    2.1.1

【2】定义个接口类,用来操作目标表的增删改查:通过 @Mapper 表示该接口类是一个 Mybatis 的 Mapper 类,通过增删改查注解 @Select @Update @Insert @Delete 对数据表进行操作;

//指定这是一个操作数据库的 mapper@Mapperpublic interface DepartmentMapper {    @Select("select * from department where id=#{id}")    public Department getDeptById(Integer id);}

【3】通过 Controller 层调用 Server 继而调用 Mapper 对数据完成操作:

@Controllerpublic class DepartmentController {    @Autowired    private DepartmentMapper mapper;    @GetMapping("/dept/{id}")    public Department getDeptById(@PathVariable("id") Integer id){        return mapper.getDeptById(id);    }}

​

上一篇:Windows系统源码深度探索,揭示核心秘密之旅

下一篇:域控服务器ip怎么设置?