• SpringBoot操作数据库


    对于数据访问层,无论是SQL还是NOSQL,SpringBoot底层都是采用SpringData的方式进行处理

    集成JDBC

    引入启动器和驱动

    <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
        data-password: 13476110270dwx
        url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver

    测试

        @Test
        void testData() throws SQLException {
            //查看数据源类型
            System.out.println(dataSource.getClass());
            //获取连接
            Connection connection=dataSource.getConnection();
            System.out.println(connection);
            //关闭连接
            connection.close();
        }

    默认的数据源是class com.zaxxer.hikari.HikariDataSource,是当前速度最快的数据源

    可以使用spring.datasource.type指定数据源类型

    JdbcTemplate

    有了数据源就可以拿到数据库连接,拿到了连接就可以使用原生的JDBC语句来操作数据库

    Spring本身对原生的JDBC进行了封装,JdbcTemplate

    数据库所有的CRUD方法都在JdbcTemplate中

    SpringBoot也提供配置好的JdbcTemplate放在容器中,只需注入就好,JdbcTemplate会自己注入数据源简化操作

    JdbcTemplate主要提供以下几类方法:

    • execute():可以执行crud语句
    • update()与batchUpdate():执行和批量执行cud语句
    • query()与queryForXXX():执行相关查询语句
    • call():执行存储过程,函数先相关语句
    @RestController
    @RequestMapping("/test")
    public class JdbcController {
        @Autowired
        JdbcTemplate jdbcTemplate;
        @GetMapping("/query")
        public List<Map<String,Object>> userList(){
            String sql="select * from employee";
            List<Map<String,Object>> maps=jdbcTemplate.queryForList(sql);
            return maps;
        }
        @GetMapping("/delete/{id}")
        public String delUser(@PathVariable("id") int id){
            String sql = "delete from employee where id=?";
            jdbcTemplate.update(sql,id);
            return "deleteOk";
        }
    }

    集成Druid

    Druid是一个数据库连接池的实现,结合了DBCP和C3P0的优点,并加入了日志监控

    将数据源切换到Druid

    导入依赖

     <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.21</version>
     </dependency>

    切换数据源,并配置Druid的属性(这些属性SpringBoot不会注入,需要手动绑定)

    spring:
    datasource:
    username: root
    data-password: 13476110270dwx
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    #Spring Boot 默认是不注入这些属性值的,需要自己绑定
    #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注入
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

    手动绑定属性

    @Configuration
    public class DruidConfig {
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDataSource(){
            return new DruidDataSource();
        }
    }

    测试

     @Autowired
        DataSource dataSource;
        @Test
        void testData() throws SQLException {
            //查看数据源类型
            System.out.println(dataSource.getClass());
            //获取连接
            Connection connection=dataSource.getConnection();
            System.out.println(connection);
            DruidDataSource druidDataSource=(DruidDataSource) dataSource;
            System.out.println(druidDataSource.getMaxActive());
            System.out.println(druidDataSource.getInitialSize());
            //关闭连接
            connection.close();
        }

    Durid数据源监控

    Druid提供一个Web界面方便查看

    配置后台管理

       //配置 Druid 监控管理后台的Servlet;
       //内置 Servlet 容器时没有web.xml文件,所以使用 Spring Boot 的注册 Servlet 方式
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean bean = new ServletRegistrationBean(new
                    StatViewServlet(), "/druid/*");
            // 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet
            // 的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
            Map<String, String> initParams = new HashMap<>();
            initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
            initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
            //后台允许谁可以访问
            //initParams.put("allow", "localhost"):表示只有本机可以访问
            //initParams.put("allow", ""):为空或者为null时,表示允许所有访问
            initParams.put("allow", "");
            //deny:Druid 后台拒绝谁访问
            //initParams.put("kuangshen", "192.168.1.20");表示禁止此ip访问
            //设置初始化参数
            bean.setInitParameters(initParams);
            return bean;
        }

    登录:localhost:8080/druib/login.html

    配置监控过滤器

        //WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
        @Bean
        public FilterRegistrationBean webStatFilter() {
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.setFilter(new WebStatFilter());
             //exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
            Map<String, String> initParams = new HashMap<>();
            initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
            bean.setInitParameters(initParams);
             //"/*" 表示过滤所有请求
            bean.setUrlPatterns(Arrays.asList("/*"));
            return bean;
        }

    Mybatis整合

    导入mybatis依赖

    <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
    </dependency>

    创建实体类

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Department {
        private int id;
        private String departmentName;
    }

    创建mapper接口

    @Mapper
    @Repository
    public interface DepartmentMapper {
        //得到全部部门
        List<Department> getDepartments();
        //通过id获得部门
        Department getDepartmentById(int id);
    }

    创建对应的mapper.xml文件

    <mapper namespace="com.deng.test.dao.DepartmentMapper">
        <select id="getDepartments" resultType="com.deng.test.pojo.Department">
            select * from department;
        </select>
        <select id="getDepartmentById" resultType="com.deng.test.pojo.Department">
            select * from department where id=#{id};
        </select>
    </mapper>

    告诉SpringBoot mapper.xml文件的位置

    mybatis:
      mapper-locations: com/deng/test/dao/*.xml

    测试

    @RestController
    public class DepartmentController {
        @Autowired
        DepartmentMapper departmentMapper;
        // 查询全部部门
        @GetMapping("/getDepartments")
        public List<Department> getDepartments(){
            return departmentMapper.getDepartments();
        }
        // 查询全部部门
        @GetMapping("/getDepartment/{id}")
        public Department getDepartmentById(@PathVariable("id") int id){
            return departmentMapper.getDepartmentById(id);
        }
    }
  • 相关阅读:
    二维数组输出10行杨辉三角
    二维数组的练习----求和
    数组的异常及处理
    二维数组在内存中的结构
    Ubuntu系统中安装Mercurial 以支持hg
    什么是插补、直线插补、联动与插补
    压力表(负压表...)
    常用接近开关的原理和分类
    VMware Ubuntu安装详细过程
    Redis+Spring缓存实例(windows环境,附实例源码及详解)
  • 原文地址:https://www.cnblogs.com/dwx-study/p/14723936.html
Copyright © 2020-2023  润新知