SpringBoot与数据访问(一)

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

整合基本JDBC与数据源

1、引入starter和MySQL驱动
<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>
2、配置application.yml
spring:
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/springboot_jdbc?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    driver‐class‐name: com.mysql.cj.jdbc.Driver
3、测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class HahaApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    public void contextLoads() throws SQLException {
        //class com.zaxxer.hikari.HikariDataSource默认数据源
        System.out.println("------------"+dataSource.getClass());

class com.zaxxer.hikari.HikariDataSource作为默认数据源
数据源的相关配置都在DataSourceProperties里面;
自动配置原理:
org.springframework.boot.autoconfigure.jdbc:
1、参考DataSourceConfiguration,根据配置创建数据源,可以使用
spring.datasource.type配置指定自定义的数据源类型;
2、SpringBoot默认可以支持;

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

3、DataSourceInitializer:ApplicationListener;
作用:
1)、runSchemaScripts();运行建表语句;
2)、runDataScripts();运行插入数据的sql语句;
默认只需要将文件命名为:

spring:
  datasource:
    username: root
    password:
    url: jdbc:mysql://localhost:3306/springboot_jdbc?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    driver‐class‐name: com.mysql.cj.jdbc.Driver
	schema‐*.sql、data‐*.sql
	默认规则:schema.sql,schema‐all.sql;
	initialization-mode: always
	schema:
		‐ classpath:department.sql
	指定位置

springboot2.0x 执行schema.sql脚本注意要加上一个配置:spring.datasource.initialization-mode=always
表示始终执行初始化。
4、操作数据库:自动配置了JdbcTemplate操作数据库

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

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

}
4、整合Druid数据源
1、引入依赖
		<!-- Druid数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
2、配置application.yml
spring:
  datasource:
    #   数据源基本配置
    username: root
    password:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url:  jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#    schema:
#      - classpath:mysql/department.sql
#      - classpath:mysql/employee.sql
#    initialization-mode: always
3、编写Druid的配置文件,并实现后台监控
@Configuration
public class DruidCongig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid(){
        return new DruidDataSource();
    }

    //配置Druid监控
    //配置一个管理后台的servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid");

        Map<String,String> map =new HashMap<>();
        map.put("loginUsername","admin");
        map.put("loginPassword","123");
        map.put("allow","");//允许所有访问
        map.put("deny","");
        bean.setInitParameters(map);
        return bean;
    }
    //配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
//        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());
//        Map<String,String> map =new HashMap<>();
//        map.put("exclusions","*.js,*.css,/druid/*");//允许通过
//        bean.setInitParameters(map);
//        bean.setUrlPatterns(Arrays.asList("/*"));
//        return bean;

        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String,String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));

        return  bean;
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值