Spring Boot 学习(一) 数据库访问

1.导入jdbc场景

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

 

jdbc中spring boot帮我们导入了,数据库连接池HikariCP、事务spring、jdbc

<dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP</artifactId>     #数据源,数据库连接池
      <version>4.0.3</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>    
      <version>5.3.8</version>
      <scope>compile</scope>
</dependency>

Spring Boot 学习(一) 数据库访问

 

 

2.导入数据库驱动,以Mysql为例

官方会对MySQL的版本进行仲裁,官方的版本是8.0.25   要与本机数据库版本一致

 

spring-boot-starter-parent   ->   spring-boot-dependencies

 

 

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/> <!-- lookup parent from repository -->
 </parent>

 

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.5.2</version>
  </parent>
 <mysql.version>8.0.25</mysql.version>

3.修改Mysql数据库版本

 

Ⅰ.固定版本 ,引入固定版本,根据本机版本进行固定更改

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
</dependency>

Ⅱ.在properties里面更改mysql的版本,properties里面进行确定各种版本信,因此在pom.xml中也这样进行自定义更改

 <properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.38</mysql.version>
    </properties>

4.分析自动配置

自动配置的类

DataSourceAutoConfiguration     //这是数据源的自动配置
  @ConditionalOnMissingBean(type = "io.r2dbc.spi.ConnectionFactory")   //非响应式数据源时函数下面函数才生效
Spring Boot 学习(一) 数据库访问
public class DataSourceAutoConfiguration {

    @Configuration(proxyBeanMethods = false)
    @Conditional(EmbeddedDatabaseCondition.class)
    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
    @Import(EmbeddedDataSourceConfiguration.class)
    protected static class EmbeddedDatabaseConfiguration {

    }

    @Configuration(proxyBeanMethods = false)
    @Conditional(PooledDataSourceCondition.class)
    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
    @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
            DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
            DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
    protected static class PooledDataSourceConfiguration {

    }

    /**
     * {@link AnyNestedCondition} that checks that either {@code spring.datasource.type}
     * is set or {@link PooledDataSourceAvailableCondition} applies.
     */
    static class PooledDataSourceCondition extends AnyNestedCondition {

        PooledDataSourceCondition() {
            super(ConfigurationPhase.PARSE_CONFIGURATION);
        }

        @ConditionalOnProperty(prefix = "spring.datasource", name = "type")
        static class ExplicitType {

        }

        @Conditional(PooledDataSourceAvailableCondition.class)
        static class PooledDataSourceAvailable {

        }

    }

    /**
     * {@link Condition} to test if a supported connection pool is available.
     */
    static class PooledDataSourceAvailableCondition extends SpringBootCondition {

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            ConditionMessage.Builder message = ConditionMessage.forCondition("PooledDataSource");
            if (DataSourceBuilder.findType(context.getClassLoader()) != null) {
                return ConditionOutcome.match(message.foundExactly("supported DataSource"));
            }
            return ConditionOutcome.noMatch(message.didNotFind("supported DataSource").atAll());
        }

    }

    /**
     * {@link Condition} to detect when an embedded {@link DataSource} type can be used.
     * If a pooled {@link DataSource} is available, it will always be preferred to an
     * {@code EmbeddedDatabase}.
     */
    static class EmbeddedDatabaseCondition extends SpringBootCondition {

        private static final String DATASOURCE_URL_PROPERTY = "spring.datasource.url";

        private final SpringBootCondition pooledCondition = new PooledDataSourceCondition();

        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            ConditionMessage.Builder message = ConditionMessage.forCondition("EmbeddedDataSource");
            if (hasDataSourceUrlProperty(context)) {
                return ConditionOutcome.noMatch(message.because(DATASOURCE_URL_PROPERTY + " is set"));
            }
            if (anyMatches(context, metadata, this.pooledCondition)) {
                return ConditionOutcome.noMatch(message.foundExactly("supported pooled data source"));
            }
            EmbeddedDatabaseType type = EmbeddedDatabaseConnection.get(context.getClassLoader()).getType();
            if (type == null) {
                return ConditionOutcome.noMatch(message.didNotFind("embedded database").atAll());
            }
            return ConditionOutcome.match(message.found("embedded database").items(type));
        }

        private boolean hasDataSourceUrlProperty(ConditionContext context) {
            Environment environment = context.getEnvironment();
            if (environment.containsProperty(DATASOURCE_URL_PROPERTY)) {
                try {
                    return StringUtils.hasText(environment.getProperty(DATASOURCE_URL_PROPERTY));
                }
                catch (IllegalArgumentException ex) {
                    // Ignore unresolvable placeholder errors
                }
            }
            return false;
        }

    }

}
View Code
  @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })   //当容器中没有配置数据源时执行下面配置 ,数据库连接池,没有才自动帮忙配置,导入了一堆组件用于配置数据库连接池
Spring Boot 学习(一) 数据库访问
@Configuration(proxyBeanMethods = false)
    @Conditional(PooledDataSourceCondition.class)
    @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
    @Import({ DataSourceConfiguration.Hikari.class, DataSourceConfiguration.Tomcat.class,
            DataSourceConfiguration.Dbcp2.class, DataSourceConfiguration.OracleUcp.class,
            DataSourceConfiguration.Generic.class, DataSourceJmxConfiguration.class })
    protected static class PooledDataSourceConfiguration {

    }
View Code

  底层配置好的数据库连接池是   HikariDataSource

  DataSourceProperties      //跟数据库有关的所有配置都在spring.datasource里面绑定
  




DataSourceTransactionManagerAutoConfiguration    //事务管理器的自动配置

JdbcTemplateAutoConfiguration                   //JdbcTemplate的自动配置,可以对数据库进行CRUD
    JdbcProperties                    //跟jdbc有关的操作都在jdbcproperties里面进行了设置
    @ConfigurationProperties(prefix = "spring.jdbc")  //可以通过修改这个配置项,来修改jdbctemplate
JndiDataSourceAutoConfiguration            //  jndi的自动配置

 

5.编写数据库相关信息的内容,写在配置文件中即可,修改配置项

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/yschoolmall
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver

6.在配置文件中编写查询超时时间,以秒作为单位

jdbc:
    template:
      query-timeout: 5

 

7.测试,因为容器中以及有了操作数据库的组件  @Bean    @Primary

 

Spring Boot 学习(一) 数据库访问

上一篇:SqlServer的sa账号被锁定


下一篇:mysql事务隔离级别和锁