6.整合jdbc

 pom.xml

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

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

yml:

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    #配置德鲁伊,后续可以配置德鲁伊相关的东西
    type: com.alibaba.druid.pool.DruidDataSource
      #SpringBoot默认是不注入这些的,需要自己绑定
      #druid数据源专有配置
    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,stat:监控统计、log4j:日志记录、wall:防御sql注入
      #如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
      #则导入log4j 依赖就行
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

jdbccontroller:

@RestController//不用跳转页面
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    //查询数据库的所有信息
    //没有实体类,数据库中的东西该如何获取
    @GetMapping("/jdbc")
    public List<Map<String,Object>> userList(){
        String sql="select * from user";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    //
    @GetMapping("/addUser")
    public String addUser(){
        String sql="insert into mybatis.user(id,name,pwd) values (5,'小王人','123456')";
        jdbcTemplate.update(sql);
        return "ok";//自动提交了事务
    }
    //花里胡哨的更新
    @GetMapping("/updateUser/{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]="xixi";
        objects[1]="123456";
        jdbcTemplate.update(sql,objects);
        return "ok";//自动提交了事务
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql="delete from mybatis.user where id=?";
        jdbcTemplate.update(sql,id);
        return "ok";//自动提交了事务
    }
}

druidConfig

@Configuration//配置文件
public class DruidConfig {
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")//yml高级注入
    public DataSource dataSource(){
        return new DruidDataSource();
    }
    //后台监控 类似于xml
    @Bean
    public ServletRegistrationBean StatViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean =
                new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登陆,账号密码
        HashMap<String, String> map = new HashMap<>();
        //增加配置 key是固定的
        map.put("loginUserName","admin");
        map.put("loginPassword","123456");
        //允许谁可以访问
        map.put("allow","");//如果参数为空就是所有人都可以访问
        bean.setInitParameters(map);//设置初始化参数
        return bean;
    }
    //过滤器
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        //可以过滤哪些请求呢
        Map<String,String> map=new HashMap<>();
        map.put("exclusions","*.js,*.css,/druid/*");
        //可以过滤哪些请求
        filterRegistrationBean.setInitParameters(map);
        return filterRegistrationBean;
    }
}

test

@SpringBootTest
class BootJdbcApplicationTests {
    //导入数据源
    @Autowired
    DataSource dataSource;
    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());//默认是hikari据说是最快的数据源
        //加了德鲁伊后得到的是class com.alibaba.druid.pool.DruidDataSource
        //获得数据库连接
        Connection connection = dataSource.getConnection();//
        System.out.println(connection);
        connection.close();
    }
}

 

posted @ 2021-06-21 22:40  一拳超人的逆袭  阅读(37)  评论(0编辑  收藏  举报