<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
</dependency>
<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
</dependency>

先在Spring的yml配置文件中配置datasource

spring:
  datasource:
    username: root
    password: 123456789z
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
   

我们先看是否配置成功

@SpringBootTest
class DemoApplicationTests {
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() {
        System.out.println(dataSource.getClass());
    }

}

ok,显示数据源是Spring自带的数据源。

写一个controller类来测试crud

这里使用restful风格

@RestController
public class TestController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @GetMapping("/user")
    public List<Map<String,Object>> userList(){
        String sql = "select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    @GetMapping("/add")
    public String addUser(){
        String sql = "insert into mybatis.user(id,name,pwd) values (5,'huahua','123456')";
        jdbcTemplate.update(sql);
        return "update-ok";
    }

    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update mybatis.user set name=?,pwd=? where id ="+id;

        Object[] objects = new Object[2];
        objects[0] = "xiaoming";
        objects[1] = "xiao";
        jdbcTemplate.update(sql,objects);
        return "update-ok";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from mybatis.user  where id = ?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}

整合druid

首先在配置文件中整合(无需强记,拿来即用),注意导入log4j否则会报错

spring:
  datasource:
    username: root
    password: 123456789z
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
      #  数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validation-query: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
      #    配置监控统计拦截的filters 去掉后监控界面sql无法统计,‘wall’用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMills=500

我们再来使用测试文件,可以看出数据源已经是druid的了

写个配置文件来配置它的监控以及其他功能

@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }
//后台监控 web.xml
    //因为springboot内置了servlet容器,所以没有web。xml替代方法servletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        //后台需要有人登录,账号密码配置
        HashMap<String,String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername","admin");//登录key是固定的
        initParameters.put("loginPassword","123456");
        //允许谁可以访问
        initParameters.put("allow","");
        //禁止谁能访问(略)
        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;

    }

    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        //可以过滤的请求
        HashMap<String, String> initParameters = new HashMap<>();
        //这些东西无需统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);
        return bean;
    }

}