0


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

在这里插入图片描述

💗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=UTCdriver-class-name: com.mysql.cj.jdbc.Driver
  • 编写controller层,测试数据库CURD功能
packagecom.wei.controller;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;importjava.util.Map;@RestControllerpublicclassJDBCController{@Autowired(required =false)JdbcTemplate jdbcTemplate;//查询数据库所有信息@GetMapping("/userList")publicList<Map<String,Object>>userList(){String sql ="select * from mybatis.user";List<Map<String,Object>>List_maps= jdbcTemplate.queryForList(sql);returnList_maps;}@GetMapping("/addUser")publicStringaddUser(){String sql ="insert into mybatis.user(id,name,pwd) values(5,'bbb',520)";
        jdbcTemplate.update(sql);return"update-ok";}@GetMapping("/updateUser/{id}")publicStringupdateUser(@PathVariableint id){String sql ="update mybatis.user set name=?,pwd=? where id="+ id;//封装Object[] objects =newObject[2];
        objects[0]="qqq";
        objects[1]="www";

        jdbcTemplate.update(sql,objects);return"update-ok";}@GetMapping("/deleteUser/{id}")publicStringdeleteUser(@PathVariableint 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=UTCdriver-class-name: com.mysql.cj.jdbc.Driver
    #切换数据源type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize:5minIdle:5maxActive:20maxWait:60000timeBetweenEvictionRunsMillis:60000minEvictableIdleTimeMillis:300000validationQuery: SELECT 1 FROM DUAL
    testWhileIdle:truetestOnBorrow:falsetestOnReturn:falsepoolPreparedStatements:true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错  java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize:20useGlobalDataSourceStat:trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  • controller层编写DruidController
packagecom.wei.config;importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.support.http.StatViewServlet;importcom.alibaba.druid.support.http.WebStatFilter;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.web.servlet.FilterRegistrationBean;importorg.springframework.boot.web.servlet.ServletRegistrationBean;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.servlet.Filter;importjavax.servlet.annotation.WebFilter;importjavax.sql.DataSource;importjava.util.HashMap;importjava.util.Map;@ConfigurationpublicclassDruidConfig{@ConfigurationProperties(prefix ="spring.datasource")@BeanpublicDataSourcedruidDataSource(){returnnewDruidDataSource();}//后台监控功能@BeanpublicServletRegistrationBeanStatViewServlet(){ServletRegistrationBean<StatViewServlet> bean =newServletRegistrationBean<>(newStatViewServlet(),"/druid/*");//后台账号密码HashMap<String,String> initParameters =newHashMap<>();//添加配置
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","123456");//允许用户访问
        initParameters.put("allow","");//禁止用户访问/*initParameters.put("","");*/
        bean.setInitParameters(initParameters);//设置初始化参数return bean;}//过滤器Filter@BeanpublicFilterRegistrationBeanwebStartFilter(){FilterRegistrationBean<Filter> bean =newFilterRegistrationBean<>();
        bean.setFilter(newWebStatFilter());//通过请求HashMap<Object,Object> initParameters =newHashMap<>();
        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
  • 测试
packagecom.wei;importorg.junit.jupiter.api.Test;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importjavax.sql.DataSource;importjavax.xml.crypto.Data;importjava.sql.SQLException;@SpringBootTestclassSpringboot04MybatisApplicationTests{@Autowired(required =false)DataSource dataSource;@TestvoidcontextLoads()throwsSQLException{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
packagecom.wei.pojo;importlombok.AllArgsConstructor;importlombok.Data;importlombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublicclassUser{privateint id;privateString name;privateString pwd;}
  • 编写mapper/UserMapper接口类
packagecom.wei.mapper;importcom.wei.pojo.User;importorg.apache.ibatis.annotations.Mapper;importorg.springframework.stereotype.Repository;importjava.util.List;@Mapper@RepositorypublicinterfaceUserMapper{List<User>queryUserList();UserqueryUserById(int id);intaddUser(User user);intupdateUser(User user);intdeleteUser(int id);}
  • 编写resources/mybatis/mapper/UserMapper.xml接口映射器
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.wei.mapper.UserMapper"><selectid="queryUserList"resultType="User">
        select *
        from mybatis.user;
    </select><selectid="queryUserById"resultType="User">
        select *
        from mybatis.user
        where id = #{id};
    </select><insertid="addUser"parameterType="User">
        insert into mybatis.user (id, name, pwd)
        values (#{id}, #{name}, #{pwd});
    </insert><updateid="updateUser"parameterType="User">
        update mybatis.user
        set name=#{name},
            pwd=#{pwd}
        where id = #{id};
    </update><deleteid="deleteUser"parameterType="int">
        delete
        from mybatis.user
        where id = #{id};
    </delete></mapper>
  • 编写Controller/UserController控制层
packagecom.wei.controller;importcom.wei.mapper.UserMapper;importcom.wei.pojo.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.List;@RestControllerpublicclassUserController{@AutowiredprivateUserMapper userMapper;//查询全部用户@GetMapping("queryUserList")publicList<User>queryUserList(){List<User> userList = userMapper.queryUserList();for(User user : userList){System.out.println(user);}return userList;}//添加用户@GetMapping("addUser")publicStringaddUser(){
        userMapper.addUser(newUser(5,"王湾","456"));return"ok";}//修改用户@GetMapping("updateUser")publicStringupdateUser(){
        userMapper.updateUser(newUser(5,"王湾","123456"));return"ok";}//删除用户@GetMapping("deleteUser")publicStringdeleteUser(){
        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

🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——

点赞

👍

收藏

⭐️

评论

📝


在这里插入图片描述


本文转载自: https://blog.csdn.net/weixin_62765017/article/details/130962581
版权归原作者 wei_shuo 所有, 如有侵权,请联系我们删除。

“SpringBoot原理分析 | Spring Data整合:JDBC、Druid、Mybatis”的评论:

还没有评论