SpringBoot入门级教程:SpringData(JDBC,Druid,Mybatis)整合,SpringSecurity和Shiro

Posted michilay

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot入门级教程:SpringData(JDBC,Druid,Mybatis)整合,SpringSecurity和Shiro相关的知识,希望对你有一定的参考价值。

说在前面

springBoot系列教程:

SpringBoot入门级教程(一):自动装配,yaml配置和静态资源导入(原理向)

SpringBoot入门级教程(二):thymeleaf,mvc配置拓展,员工系统的实现

SpringBoot入门级教程(三):SpringData(JDBC,Druid,Mybatis)整合,SpringSecurity和Shiro

SpringBoot入门级教程(四):异步、邮件任务、定时任务、分布式RPC概述以及Dubbo和Zookeeper

github地址:
https://github.com/Michilay/SpringBoot.git

Spring Data

springboot不管是关联SQL或者是NoSQL数据库,都是以data的形势

整合JDBC

  • 创建项目

记得添加JDBC API和mysql Driver的依赖,还有WEB依赖,如果在创建的时候没有添加,也可以在pom中添加,不过尽量不要以这种方式,web依赖最好在创建项目的时候添加,以免发生一些web相关的bug

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 使用idea关联数据库

  • 进行数据库相关配置

    spring:
      datasource:
        username: root
        password: 数据库密码
        url: jdbc:mysql://localhost:3306/count_db?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
    
  • 自动装配dataSource,测试springBoot默认的数据源

    package com.michilay;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    import javax.sql.DataSource;
    
    @SpringBootTest
    class Springboot04DataApplicationTests {
    
    
        private DataSource dataSource;
        @Autowired
        public Springboot04DataApplicationTests(DataSource dataSource) {
            this.dataSource = dataSource;
        }
    
        @Test
        void contextLoads() {
    //        查看默认的数据源
            System.out.println(dataSource.getClass());
            Connection connection = dataSource.getConnection();
            System.out.println(connection);
            connection.close();
        }
    
    }
    

    class com.zaxxer.hikari.HikariDataSource
    2021-08-23 10:01:46.649 INFO 2752 — [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting…
    2021-08-23 10:01:48.858 INFO 2752 — [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
    HikariProxyConnection@1582330795 wrapping com.mysql.cj.jdbc.ConnectionImpl@3c4262d1
    2021-08-23 10:01:48.965 INFO 2752 — [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated…
    2021-08-23 10:01:48.973 INFO 2752 — [extShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

    hikari是data默认数据源,和dbcp,速度最快

  • jar包下XXXXTemplate表示就是就是SpringBoot已经帮我们配置好的模板bean,CRUD方法封装在里面,直接拿过来用就可以

    例如我们要使用JDBC的数据源,找到Maven下的spring-boot-autoconfigure-2.3.7.RELEASE.jar,进入org找到JDBC包,找到JdbcTemplateConfiguration类,可以看到以下代码

    @Configuration(
        proxyBeanMethods = false
    )
    //只会有一个Bean生效
    @ConditionalOnMissingBean({JdbcOperations.class})
    class JdbcTemplateConfiguration {
        JdbcTemplateConfiguration() {
        }
    //已经注册了Bean可以直接使用
        @Bean
        @Primary
        //只需要数据源和相关配置,数据源springboot帮忙做了,配置上文也进行了
        JdbcTemplate jdbcTemplate(DataSource dataSource, JdbcProperties properties) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            Template template = properties.getTemplate();
            jdbcTemplate.setFetchSize(template.getFetchSize());
            jdbcTemplate.setMaxRows(template.getMaxRows());
            if (template.getQueryTimeout() != null) {
                jdbcTemplate.setQueryTimeout((int)template.getQueryTimeout().getSeconds());
            }
    
            return jdbcTemplate;
        }
    }
    

    我们可以直接使用这个Bean进行操作就可以了

  • 使用原生JDBC借助springboot封装的方法进行crud的操作

    package com.michilay.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.util.List;
    import java.util.Map;
    
    @RestController
    public class JdbcController {
    
        @RequestMapping("/t1")
        public String test(){
            return "hello springboot";
        }
        @Autowired
        JdbcTemplate jdbcTemplate;
    //  查询
        @GetMapping("/userList")
        public List<Map<String,Object>> userList(){
            String sql = "select * from count_db.account";
            List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
            return maps;
        }
    //  添加
        @GetMapping("/addUser")
        public String addUser(){
            String sql = "insert into count_db.account(userId,userName,userPwd,money) values (2,'123123','123123',123.1)";
            jdbcTemplate.update(sql);
    //        自动提交事务
            return "add OK!";
        }
    
        @GetMapping("/updateUser/{id}")
        public String updateUser(@PathVariable("id") int id){
            String sql = "update count_db.account set userName =?,userPwd=?,money=?  where userId=" + id;
            Object[] objects = new Object[3];
            objects[0] = "mcly111";
            objects[1] = "mcly1111";
            objects[2] = "123.123";
            jdbcTemplate.update(sql,objects);
            return "update OK!";
        }
    
        @GetMapping("/deleteUser/{id}")
        public String deleteUser(@PathVariable("id") int id){
            String sql = "delete from count_db.account where userId = ?";
            jdbcTemplate.update(sql,id);
            return "delete OK!";
        }
    }
    

整合Druid

Druid介绍

druid是阿里巴巴开源平台上一个数据库链接池的实现,结合了C3P0、DBCP、PROXOOL等DB池的优点,并且加入了日志监控

Druid使用

  • 导入Druid依赖

    <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.6</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
  • 配置数据源

    # 数据源配置
    spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
    
  • 测试查看数据源

    class com.alibaba.druid.pool.DruidDataSource
    2021-08-23 11:26:03.089 INFO 14580 — [ main] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited
    com.mysql.cj.jdbc.ConnectionImpl@608bc8f8

  • 配置Druid专属配置

    spring:
      datasource:
        username: root
        password: 数据库密码
        url: jdbc:mysql://localhost:3306/count_db?serverTimezone=UTC&userUnicode=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: 6000
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 1 FROM DUAL
        testWhileIdle: true
        testOnBorrow: false
        poolPreparedStatements: true
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20
        userGlobalDataSourceStat: true
        connectionProperties: druid.stat.mergeSql=true.druid.stat.slowSqlMillis=500
    
  • 编写Druid配置类

    package com.michilay.config;
    
    
    import com.alibaba.druid.pool.DruidDataSource;
    import com.alibaba.druid.support.http.StatViewServlet;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import javax.sql.DataSource;
    import java.util.HashMap;
    
    @Configuration
    public class DruidConfig {
    
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDataSource(){
            return new DruidDataSource();
        }
    //    后台监控
        @Bean
        public ServletRegistrationBean statViewServlet(){
            ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
    //        后台需要有人登录账号密码
            HashMap<String, String> initParameters = new HashMap<>();
    //        用户名密码的值固定
            initParameters.put("loginUsername","admin");
            initParameters.put("loginPassword","123");
    //        允许谁可以访问
            initParameters.put("allow","");
    
    
    
    //        初始化参数
            bean.setInitParameters(initParameters);
            return bean;
        }
    
    
    }
    
  • 运行服务器,浏览器输入

    http://localhost:8080/druid/sql.html

整合Mybatis

  • 创建springboot项目,导入mybatis、web、jdbc、mysql等依赖

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.1.4</version>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    
  • 配置相关信息

    # 应用名称
    spring.application.name=springboot-05-mybatis
    # 数据库驱动:
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    # 数据源名称
    spring.datasource.name=defaultDataSource
    # 数据库连接地址
    spring.datasource.url=jdbc:mysql://localhost:3306/count_db?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
    # 数据库用户名&密码:
    spring.datasource.username=root
    spring.datasource.password=数据库密码
    #下面这些内容是为了让MyBatis映射
    #指定Mybatis的Mapper文件
    mybatis.mapper-locations=classpath:mapper/*.xml
    #指定Mybatis的实体目录
    mybatis.type-aliases-package=com.michilay.pojo
    # 应用服务 WEB 访问端口
    server.port=8080
    
  • 编写实体类和对应的mapper接口

    package com.michilay.pojo;
    
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    import org.springframework.stereotype.Component;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private int userId;
        private String userName;
        private String userPwd;
        private Double money;
    }
    
    package com.michilay.mapper;
    
    
    import com.michilay.pojo.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    
    import java.util.List;
    
    @Mapper
    @Repository
    public interface UserMapper {
    
        List<User> findAll();
        User findUserById(int id);
        int addUser(User user);
        int updateUser(User user);
        int deleteUser(int id);
    }
    
  • 在编写对应的service层和实现类

    package com.michilay.service;
    
    import com.michilay.pojo.User;
    
    import java.util.List;
    
    public interface UserService {
        List<User> findAll();
        User findUserById(int id);
        int addUser(User user);
        int updateUser(User user);
        int deleteUser(int id);
    }
    
    package com.michilay.service;
    
    import com.michilay.mapper.UserMapper;
    import com.michilay.pojo.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    
    @Service("userService")
    public class UserServiceImpl implements UserService{
    
        UserMapper userMapper;
        @Autowired
        public UserServiceImpl(UserMapper userMapper) {
            this.userMapper = userMapper;
        }
    
        @Override
        public List<User> findAll() {
            return userMapper.findAll();
        }
    
        @Override
        public User findUserById(int id) {
            return userMapper.findUserById(id);
        }
    
        @Override
        public int addUser(User user) {
            return userMapper.addUser(user);
        }
    
        @Override
        public int updateUser(User user) {
            return userMapper.updateUser(user);
        }
    
        @Override
        public int deleteUser(int id) {
            return userMapper.deleteUser(id);
        }
    }
    
  • 编写实现增删改查的mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.michilay.mapper.UserMapper">
    
        <select id="findAll" resultType="User">
            select * from count_db.account
        </select>
    
        以上是关于SpringBoot入门级教程:SpringData(JDBC,Druid,Mybatis)整合,SpringSecurity和Shiro的主要内容,如果未能解决你的问题,请参考以下文章

    Spring Boot 入门 (5) 深入Actuator

    SpringBoot快速上手——《一》:初始SpringBoot,实现入门级程序

    SpringBoot快速上手——《一》:初始SpringBoot,实现入门级程序

    为啥选择Spring Boot作为微服务的入门级微框架

    SpringBoot入门极简教程开篇

    小白入门SpringBoot极简教程开篇