SpringBoot(8)—— 数据访问(数据库相关)

数据访问(数据库相关)


一、JDBC

1. SpringBoot默认使用JDBC作为数据源
2. 通过加载建表SQL语句来建表

deartment.sql:建表语句

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `departmentName` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

方法一:将.sql文件命名为schema.sql或者schema-all.sql,放在resources下即可加载

方法二:在全局配置文件中指定SQL文件的位置

application.yml

spring:
     datasource:
       schema:
         - classpath:department.sql
     type: com.zaxxer.hikari.HikariDataSource

注意:
(1)同时需要加上type: com.zaxxer.hikari.HikariDataSource配置才能生效
(2)classpath:冒号后不能有空格

3. SpringBoot自动配置了JdbcTemplate操作数据库

只需要将JdbcTemplate自动注入到容器中,即可调用其方法(如JdbcTemplate.queryForList

/controller/HelloController

@Controller
public class HelloController {

    @Autowired
    JdbcTemplate jdbcTemplate;

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

        return list.get(0);
    }
}

二、Druid

1. 切换为Druid数据源

pom.xml

	<dependency>
         <groupId>com.alibabagroupId>
         <artifactId>druidartifactId>
         <version>1.1.22version>
     dependency>

application.yml

spring:
     type: com.alibaba.druid.pool.DruidDataSource
2. Druid数据源的配置

(1)创建自定义配置类DruidConfig,使用@Configuration注解
(2)创建一个DruidDataSource对象并返回,在该方法上加上@ConfigurationProperties(prefix = "spring.datasource")指定在pom文件中的配置是以spring.datasource开头的相关配置

DruidConfig

@Configuration
public class DruidConfig {

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

application.yml

spring:
  datasource:
    
    #   数据源其他配置
    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
3. 配置Druid的管理后台和监控

(1)配置一个管理后台的Servlet
- 使用ServletRegistrationBean来注册Servlet
- public ServletRegistrationBean(T servlet, String... urlMappings):通过该构造方法,传入StatViewServlet对象和/druid/*的url,处理druid下的所有请求
- 将初始化配置放在Map中(配置项参考ResourceServlet类)
- 用ServletRegistrationBean.setInitParameters加载初始化配置
- 最终返回ServletRegistrationBean的Bean容器对象,并放到容器中

(2)配置一个监控的filter
- 使用FilterRegistrationBean来注册Filter
- FilterRegistrationBean.setFilter(T filter):通过该方法,传入WebStatFilter对象
- 将初始化配置放在Map中(配置项参考WebStatFilter类)
- 用FilterRegistrationBean.setInitParameters加载初始化配置
- FilterRegistrationBean.setUrlPatterns:设置拦截的请求
- 最终返回FilterRegistrationBean的Bean容器对象,并放到容器中

DruidConfig

@Configuration
public class DruidConfig {

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

    // 1. 配置一个管理后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        // 处理druid下的所有请求
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        // 首先设置好初始化配置到map中
        Map<String, String> initParms = new HashMap<>();
        initParms.put("loginUsername", "admin");
        initParms.put("loginPassword", "123456");
        // 默认允许所有访问
//        initParms.put("allow", "localhost");

        // 使用ServletRegistrationBean来加载初始化配置
        bean.setInitParameters(initParms);

        return bean;
    }

    // 2. 配置一个监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParms = new HashMap<>();
        // 不拦截的请求
        initParms.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParms);

        // 拦截所有请求(/*)
        bean.setUrlPatterns(Arrays.asList("/*"));

        return bean;
    }
}

application.yml

spring:
  datasource:
    
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

效果:
http://localhost:8080/druid:可以登录Druid的后台管理

你可能感兴趣的:(Spring,Boot)