SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis_bc

💗wei_shuo的个人主页

💫wei_shuo的学习社区

🌐Hello World !


Spring Data

Spring Data是一个用于简化数据库访问和操作的开源框架,为开发人员提供了一种通用的方式来处理不同类型的数据存储,例如关系型数据库(如MySQL、PostgreSQL、Oracle)和非关系型数据库(如MongoDB、Cassandra、Redis)等。Spring Data还提供了许多有用的特性和工具,例如数据持久化、事务管理、查询和分页等功能,以及对多种数据访问技术的支持,如JPA、Hibernate、MyBatis等

Spring Data框架的核心思想是通过使用Repository模式,将数据访问逻辑从业务逻辑中分离出来,从而简化应用程序的开发和维护;开发人员只需要定义一个接口,继承Spring Data提供的Repository接口,即可获得许多常用的数据库操作方法,如增删改查、分页查询等;Spring Data框架会根据接口定义动态生成实现类,从而使得开发人员可以专注于业务逻辑的实现,而不用关注底层的数据访问细节

Spring Data是一个非常强大和灵活的数据访问框架,可以帮助开发人员更加高效地访问和操作各种类型的数据存储,同时提供了许多有用的特性和工具,能够大大简化应用程序的开发和维护

整合JDBC

JDBC是Java语言中用于与关系型数据库交互的一种标准API;通过JDBC,Java程序可以连接到不同的数据库系统,如MySQL、Oracle、PostgreSQL等,并进行数据的增、删、改、查等操作
JDBC API包括两部分:JDBC驱动程序和Java应用程序接口。JDBC驱动程序是连接Java应用程序和数据库的桥梁,它们负责与数据库进行通信,并将数据转换为Java程序可以理解的格式。Java应用程序接口则是Java程序访问数据库的核心,它提供了一组标准的类和方法,用于与数据库进行交互
• resources文件夹下创建application.yml文件
spring:
  datasource:
    username: "root"
    password: "root"
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
• 编写controller层,测试数据库CURD功能
package com.wei.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.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JDBCController {

    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

    //查询数据库所有信息
    @GetMapping("/userList")
    public List<Map<String, Object>> userList() {
        String sql = "select * from mybatis.user";
        List<Map<String, Object>> List_maps = jdbcTemplate.queryForList(sql);
        return List_maps;
    }


    @GetMapping("/addUser")
    public String addUser() {
        String sql = "insert into mybatis.user(id,name,pwd) values(5,'bbb',520)";
        jdbcTemplate.update(sql);
        return "update-ok";
    }

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

        //封装
        Object[] objects = new Object[2];
        objects[0] = "qqq";
        objects[1] = "www";

        jdbcTemplate.update(sql,objects);
        return "update-ok";
    }

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

整合Druid

Druid是一个开源的高性能、高可靠性的分布式列存储系统,主要用于支持实时数据探索和分析;提供了一种可扩展的、快速的、实时的数据存储和查询技术,支持高吞吐量和低延迟的查询,并能够处理大规模数据的实时流式处理。Druid的数据存储方式基于列存储,具有高效的压缩算法和索引机制,能够提供高效的数据查询和聚合操作
Druid的架构包括数据源、数据处理和数据查询三个组件。数据源负责数据的采集和预处理,数据处理组件将数据转换为Druid的列存储格式,并进行索引和压缩,数据查询组件则提供了一个SQL查询引擎和RESTful API,用于查询和聚合存储在Druid中的数据;被广泛用于实时数据分析和探索领域,如广告分析、在线推荐、监控和运营等
• application.yml
spring:
  datasource:
    username: "root"
    password: "root"
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    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注入
    #如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
• controller层编写DruidController
package com.wei.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.annotation.WebFilter;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@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","123456");
        //允许用户访问
        initParameters.put("allow","");
        //禁止用户访问
        /*initParameters.put("","");*/
        bean.setInitParameters(initParameters);   //设置初始化参数
        return bean;
    }

    //过滤器Filter
    @Bean
    public FilterRegistrationBean webStartFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //通过请求
        HashMap<Object, Object> initParameters = new HashMap<>();
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        return bean;
    }
}

整合Mybatis

• springboot-mybatis依赖
<!--springboot-mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.1</version>
        </dependency>
• 配置数据库连接application.properties
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
• 测试
package com.wei;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.sql.SQLException;

@SpringBootTest
class Springboot04MybatisApplicationTests {

    @Autowired(required = false)
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        System.out.println("=================");
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }
}
• 依赖导入pom.xml
<dependencies>
        <!--springboot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--springboot-mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    	<!--jdbc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
		<!--mysql-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
    	<!--test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
• 编写pojo/user
package com.wei.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
}
• 编写mapper/UserMapper接口类
package com.wei.mapper;

import com.wei.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {

    List<User> queryUserList();

    User queryUserById(int id);

    int addUser(User user);

    int updateUser(User user);

    int deleteUser(int id);

}
• 编写resources/mybatis/mapper/UserMapper.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.wei.mapper.UserMapper">

    <select id="queryUserList" resultType="User">
        select *
        from mybatis.user;
    </select>

    <select id="queryUserById" resultType="User">
        select *
        from mybatis.user
        where id = #{id};
    </select>

    <insert id="addUser" parameterType="User">
        insert into mybatis.user (id, name, pwd)
        values (#{id}, #{name}, #{pwd});
    </insert>

    <update id="updateUser" parameterType="User">
        update mybatis.user
        set name=#{name},
            pwd=#{pwd}
        where id = #{id};
    </update>

    <delete id="deleteUser" parameterType="int">
        delete
        from mybatis.user
        where id = #{id};
    </delete>

</mapper>
• 编写Controller/UserController控制层
package com.wei.controller;

import com.wei.mapper.UserMapper;
import com.wei.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //查询全部用户
    @GetMapping("queryUserList")
    public List<User> queryUserList() {
        List<User> userList = userMapper.queryUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        return userList;
    }

    //添加用户
    @GetMapping("addUser")
    public String addUser() {
        userMapper.addUser(new User(5, "王湾", "456"));
        return "ok";
    }

    //修改用户
    @GetMapping("updateUser")
    public String updateUser() {
        userMapper.updateUser(new User(5, "王湾", "123456"));
        return "ok";
    }

    //删除用户
    @GetMapping("deleteUser")
    public String deleteUser() {
        userMapper.deleteUser(5);
        return "ok";
    }
}
• 编写resources/application.properties:配置数据源、整合mybatis
#配置数据源
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#整合mybatis
mybatis.type-aliases-package=com.wei.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——点赞👍收藏⭐️评论📝


SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis_spring boot_02