SpringBoot——数据访问

优质博文:IT-BLOG-CN

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

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

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

<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中配置数据源相关信息:

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默认支持一下数据源:DataSourceHikariDataSourceBasicDataSource。用户也可以自定义数据源:如下可知是通过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<DataSourceInitializedEvent> {
//......
}

DataSourceInitializer的两个主要作用:①、运行建表语句;②、运行操作数据的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() + ")");
        }
    }

}
//运行操作数据的 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】进行数据表创建时,默认只需要将文件命名为: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数据源,首先需要引入依赖:

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

【1】创建项目:选中webmybatismysqljdbc模块的starts;在pom.xml中会发现mybatisspringboot的整合依赖:这个依赖并不是以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表示该接口类是一个MybatisMapper类,通过增删改查注解@Select @Update @Insert @Delete对数据表进行操作;

//指定这是一个操作数据库的 mapper
@Mapper
public interface DepartmentMapper {

    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);
}

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

@Controller
public class DepartmentController {

    @Autowired
    private DepartmentMapper mapper;

    @GetMapping("/dept/{id}")
    public Department getDeptById(@PathVariable("id") Integer id){
        return mapper.getDeptById(id);
    }
}

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年12月5日
下一篇 2023年12月5日

相关推荐