SpringBoot通过JDBC访问数据

一、引入JDBC相关jar

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

二、主配置文件配置数据源

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.43.118:3307/jdbc
    driver-class-name: com.mysql.jdbc.Driver

三、测试是否连接

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDataJdbcApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    public void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

}

 

 默认是用org.apache.tomcat.jdbc.pool.DataSource作为数据源,数据源的相关配置都在DataSourceProperties里面。

四、数据源自动配置原理

查看org.springframework.boot.autoconfigure.jdbc:

1、参考DataSourceConfiguration,根据配置创建数据源,默认使用Tomcat连接池,可以使用spring.datasource.type指定自定义的数据源类型;

2、SpringBoot默认可以支持:

org.apache.tomcat.jdbc.pool.DataSource、HikariDataSource、BasicDataSource

3、自定义数据源类型

/**
 * Generic DataSource configuration.
 */
@ConditionalOnMissingBean(DataSource.class)
@ConditionalOnProperty(name = "spring.datasource.type")
static class Generic {

   @Bean
   public DataSource dataSource(DataSourceProperties properties) {
       //使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
      return properties.initializeDataSourceBuilder().build();
   }

}

五、SpringBoot默认读取sql文件配置

查看配置类:DataSourceInitializer:ApplicationListener

可知:

    1)、runSchemaScripts();运行建表语句;

    2)、runDataScripts();运行插入数据的sql语句;

只需要将文件命名为:

schema-*.sql、data-*.sql

默认读取:schema.sql,schema-all.sql

可以在全局配置文件中指定:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://192.168.43.118:3307/jdbc
    driver-class-name: com.mysql.jdbc.Driver
    schema:
      - classpath:department.sql

六、默认自动配置了JdbcTemplate操作数据库

查看:JdbcTemplateAutoConfiguration可知

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

    @Bean
    @Primary
    @ConditionalOnMissingBean({NamedParameterJdbcOperations.class})
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(this.dataSource);
    }

编写案例测试:

@Controller
public class TestController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @ResponseBody
    @GetMapping("/query")
    public Map<String,Object> map(){
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from department");
        return list.get(0);
    }
 
  
  

猜你喜欢

转载自blog.csdn.net/xm393392625/article/details/88529201