• [SpringBoot] SpringBoot JDBC访问数据库


    ✨✨个人主页:沫洺的主页

    📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏 

                               📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏

                               📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏     

    💖💖如果文章对你有所帮助请留下三连✨✨

    🍃Spring Boot JDBC访问数据库 

    对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 都默认采用整合 Spring Data 的方式进行统一处理,通过大量自动配置,来简化我们对数据访问层的操作,我们只需要进行简单的设置即可实现对书层的访问。

    引入JDBC启动器

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-jdbcartifactId>
    4. dependency>

    数据库驱动

    1. <dependency>
    2. <groupId>mysqlgroupId>
    3. <artifactId>mysql-connector-javaartifactId>
    4. <scope>runtimescope>
    5. dependency>

    配置数据源application.yml

    1. spring:
    2. datasource:
    3. driver-class-name: com.mysql.cj.jdbc.Driver
    4. url: jdbc:mysql://localhost:3306/db5?useSSL=false&useServerPrepStmts=true
    5. username: root
    6. password: 123456

    测试

    Spring Boot 提供了一个名为 JdbcTemplate 的轻量级数据访问工具,它是对 JDBC 的封装。Spring Boot 对 JdbcTemplate 提供了默认自动配置,我们可以直接使用 @Autowired 或构造函数将它注入到 bean 中使用。

    单元测试

    1. @SpringBootTest
    2. class ApplicationTests {
    3. @Autowired
    4. private DataSource dataSource;
    5. @Autowired
    6. private JdbcTemplate jdbcTemplate;
    7. @Test
    8. void contextLoads() throws SQLException {
    9. System.out.println("默认数据源:" + dataSource.getClass());
    10. System.out.println("数据库连接实例:" + dataSource.getConnection());
    11. // 访问数据库
    12. Integer i = jdbcTemplate.queryForObject("SELECT count(*) FROM user", Integer.class);
    13. System.out.println("user 表中共有" + i + "条数据。");
    14. }
    15. }

    🍂Spring Boot整合Druid数据源 

    Druid 是阿里巴巴推出的一款开源的高性能数据源产品,Druid 支持所有 JDBC 兼容的数据库,包括 Oracle、MySQL、SQL Server 和 H2 等等。Druid 不仅结合了 C3P0、DBCP 和 PROXOOL 等数据源产品的优点,同时还加入了强大的监控功能。通过 Druid 的监控功能,可以实时观察数据库连接池和 SQL 的运行情况,帮助用户及时排查出系统中存在的问题。

    使用 Druid Spring Boot Starter 将 Druid 与 Spring Boot 整合

    引入 Druid Spring Boot Starter 依赖

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>druid-spring-boot-starterartifactId>
    4. <version>1.2.9version>
    5. dependency>

    配置属性

    1. #数据库连接信息配置
    2. spring:
    3. datasource:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. username: root
    6. password: 123456
    7. url: jdbc:mysql://localhost:3306/db5
    8. druid:
    9. initial-size: 10 # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    10. min-idle: 10 # 最小连接池数量 最小空闲数量
    11. maxActive: 200 # 最大连接池数量 最大活跃连接数
    12. maxWait: 60000 # 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置
    13. timeBetweenEvictionRunsMillis: 60000 # 检查空闲连接的频率.Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。
    14. minEvictableIdleTimeMillis: 300000 # 连接的最小生存时间.连接保持空闲而不被驱逐的最小时间
    15. validationQuery: SELECT 1 # 验证数据库服务可用性的sql.用来检测连接是否有效的sql 因数据库方言而差, 例如 oracle 应该写成 SELECT 1 FROM DUAL
    16. testWhileIdle: true # 申请连接时检测空闲时间,根据空闲时间再检测连接是否有效.建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRun
    17. testOnBorrow: false # 申请连接时直接检测连接是否有效.申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    18. testOnReturn: false # 归还连接时检测连接是否有效.归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    19. poolPreparedStatements: true # 开启PSCache
    20. maxPoolPreparedStatementPerConnectionSize: 20 #设置PSCache值
    21. connectionErrorRetryAttempts: 3 # 连接出错后再尝试连接三次
    22. breakAfterAcquireFailure: true # 数据库服务宕机自动重连机制
    23. timeBetweenConnectErrorMillis: 300000 # 连接出错后重试时间间隔
    24. asyncInit: true # 异步初始化策略
    25. remove-abandoned: true # 是否自动回收超时连接
    26. remove-abandoned-timeout: 1800 # 超时时间(以秒数为单位) 超过此值后,druid将强制回收该连接
    27. transaction-query-timeout: 6000 # 事务超时时间
    28. filters: stat,wall,log4j2
    29. connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    30. stat-view-servlet:
    31. enabled: true #是否开启内置监控页面,默认值为 false
    32. url-pattern: "/druid/*" #StatViewServlet 的映射路径,即内置监控页面的访问地址
    33. allow: 127.0.0.1 #白名单
    34. deny: #黑名单
    35. reset-enable: false #是否启用重置按钮
    36. login-username: admin #内置监控页面的登录页用户名 username
    37. login-password: admin #内置监控页面的登录页密码 password
    38. web-stat-filter:
    39. enabled: true #是否开启内置监控中的 Web-jdbc 关联监控的数据
    40. url-pattern: "/*" #匹配路径
    41. exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*" #排除路径
    42. session-stat-enable: true #是否监控session

    🍁Spring Boot整合MyBatis

    MyBatis 是一个半自动化的 ORM 框架,所谓半自动化是指 MyBatis 只支持将数据库查出的数据映射到 POJO 实体类上,而实体到数据库的映射则需要我们自己编写 SQL 语句实现,相较于Hibernate 这种完全自动化的框架,Mybatis 更加灵活,我们可以根据自身的需求编写 sql 语句来实现复杂的数据库操作。

    随着 Spring Boot 越来越流行,越来越多的被厂商及开发者所认可,MyBatis 也开发了一套基于 Spring Boot 模式的 starter:mybatis-spring-boot-starter。

    引入依赖

    1. <dependency>
    2. <groupId>org.mybatis.spring.bootgroupId>
    3. <artifactId>mybatis-spring-boot-starterartifactId>
    4. <version>2.1.4version>
    5. dependency>

    (jdbc,mysql驱动,druid)

    1. <dependency>
    2. <groupId>org.springframework.datagroupId>
    3. <artifactId>spring-data-jdbcartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>com.alibabagroupId>
    7. <artifactId>druid-spring-boot-starterartifactId>
    8. <version>1.2.9version>
    9. dependency>
    10. <dependency>
    11. <groupId>mysqlgroupId>
    12. <artifactId>mysql-connector-javaartifactId>
    13. <scope>runtimescope>
    14. dependency>

    application.yml配置 MyBatis

    1. #数据库连接信息配置
    2. spring:
    3. datasource:
    4. driver-class-name: com.mysql.cj.jdbc.Driver
    5. url: jdbc:mysql://localhost:3306/db5?useSSL=false&useServerPrepStmts=true
    6. username: root
    7. password: 123456
    8. druid:
    9. initial-size: 10 # 初始化时建立物理连接的个数
    10. min-idle: 10 # 最小连接池数量
    11. maxActive: 200 # 最大连接池数量
    12. maxWait: 60000 # 获取连接时最大等待时间,单位毫秒
    13. #映射文件所在位置
    14. mybatis:
    15. mapper-locations: classpath:mapper/*Mapper.xml
    16. #别名
    17. type-aliases-package: com.moming.entity
    18. #配置日志级别
    19. logging:
    20. level:
    21. com.moming: debug

    示例

    AccountEntity

    1. package com.moming.entity;
    2. import lombok.Data;
    3. import java.math.BigDecimal;
    4. @Data
    5. public class AccountEntity {
    6. private Integer id;
    7. private String name;
    8. private BigDecimal money;
    9. }

    AccountDto

    1. package com.moming.dto;
    2. import lombok.Data;
    3. import java.math.BigDecimal;
    4. @Data
    5. public class AccountDto {
    6. private Integer id;
    7. private String name;
    8. private BigDecimal money;
    9. }

    AccountMapper.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.moming.dao.AccountDao">
    6. <select id="select" resultType="AccountEntity">
    7. select id,name,money from account
    8. select>
    9. mapper>

    AccountDao

    1. package com.moming.dao;
    2. import com.moming.entity.AccountEntity;
    3. import org.apache.ibatis.annotations.Mapper;
    4. import java.util.List;
    5. @Mapper
    6. public interface AccountDao{
    7. List select();
    8. }

    AccountService

    1. package com.moming.service;
    2. import com.moming.dto.AccountDto;
    3. import java.util.List;
    4. public interface AccountService {
    5. List select();
    6. }

    AccountServiceImpl

    1. package com.moming.service.impl;
    2. import cn.hutool.core.bean.BeanUtil;
    3. import com.moming.dao.AccountDao;
    4. import com.moming.dto.AccountDto;
    5. import com.moming.entity.AccountEntity;
    6. import com.moming.service.AccountService;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Service;
    9. import java.util.List;
    10. @Service
    11. public class AccountServiceImpl implements AccountService {
    12. @Autowired
    13. private AccountDao accountDao;
    14. @Override
    15. public List select() {
    16. List entityList = accountDao.select();
    17. List accountDtoList = BeanUtil.copyToList(entityList, AccountDto.class);
    18. return accountDtoList;
    19. }
    20. }

    AccountController

    1. package com.moming.controller;
    2. import com.moming.dto.AccountDto;
    3. import com.moming.service.AccountService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import java.util.List;
    9. @RestController
    10. @RequestMapping("/api/account")
    11. public class AccountController {
    12. @Autowired
    13. private AccountService accountService;
    14. @GetMapping("/select")
    15. public List select(){
    16. return accountService.select();
    17. }
    18. }

    补充

    启动类@MapperScan

    在不使用@MapperScan前,我们需要直接在Mapper/Dao接口类上面添加注解@Mapper,这种方式要求每一个Mapper/Dao接口类都需要添加此注解,非常麻烦,属于重复劳动。通过使用@MapperScan注解,可以让我们不用为每个Mapper/Dao接口类都添加@Mapper注解

    1. package com.moming;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. @SpringBootApplication
    6. @MapperScan("com.moming.dao")
    7. public class App2 {
    8. public static void main(String[] args) {
    9. SpringApplication.run(App2.class, args);
    10. }
    11. }
    1. package com.moming.dao;
    2. import com.moming.entity.AccountEntity;
    3. import org.apache.ibatis.annotations.Mapper
    4. import java.util.List;
    5. //@Mapper
    6. public interface AccountDao{
    7. List select();
    8. }

    🍀Spring Boot事务 

    在spring boot中 要使用事务 直接使用注解@Transactional既可,无需要做其它任何配置。是因为默认已经开启,下图可以看到默认true,这个注解是用来声明这个类或者方法需要开启事务。

    @EnableTransactionManagement // 等同于xml配置方式的

    这个注解可以放在springboot的启动类上,也可以放在配置类上。他的作用是开启事务管理。他是spring-tx中的注解,不是springboot中的注解。如果你添加的是 spring-boot-starter-jdbc 依赖(mybatis框架也会依赖jdbc),框架会默认注入 DataSourceTransactionManager 实例。如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。springboot的autoconfigure是默认已经有这个注解的,所以在springboot中不需要再次使用这个注解。

    详情可参考:@Transactional事务管理可以不使用@EnableTransactionalManagement开启

    所以启动类上不加@EnableTransactionManagement注解,也可以进行事务管理

    测试

    AccountDao

    1. @Mapper
    2. public interface AccountDao{
    3. @Update("update account set money=money-#{money} where name=#{fromName}")
    4. Integer minusMoney(String fromName, BigDecimal money);
    5. @Update("update account set money=money+#{money} where name=#{toName}")
    6. Integer addMoney(String toName, BigDecimal money);
    7. }

    AccountService

    1. public interface AccountService {
    2. void transfer();
    3. }

    AccountServiceImpl

    1. @Service
    2. public class AccountServiceImpl implements AccountService {
    3. @Autowired
    4. private AccountDao accountDao;
    5. @Transactional
    6. @Override
    7. public void transfer() {
    8. accountDao.minusMoney("张三", BigDecimal.valueOf(200));
    9. //int a = 1/0;
    10. accountDao.addMoney("李四", BigDecimal.valueOf(200));
    11. }
    12. }

    AccountController

    1. @RestController
    2. @RequestMapping("/api/account")
    3. public class AccountController {
    4. @Autowired
    5. private AccountService accountService;
    6. @GetMapping("/transfer")
    7. public String transfer(){
    8. accountService.transfer();
    9. return "转账成功";
    10. }
    11. }

    转账异常,事务回滚

    1. @Service
    2. public class AccountServiceImpl implements AccountService {
    3. @Autowired
    4. private AccountDao accountDao;
    5. @Transactional
    6. @Override
    7. public void transfer() {
    8. accountDao.minusMoney("张三", BigDecimal.valueOf(200));
    9. int a = 1/0;
    10. accountDao.addMoney("李四", BigDecimal.valueOf(200));
    11. }
    12. }

  • 相关阅读:
    Mygin实现分组路由Group
    Spring Gateway 根据服务名路由失败,报错 Service Unavailable, status=503
    《QEMU/KVM源码分析与应用》读书笔记3 —— 第一章 QEMU与KVM概述
    主机ping不通虚拟机,虚拟机可以ping同主机
    若依微服务上传图片文件代理配置
    主流新闻媒体有哪些,怎么邀约记者
    2022杭电多校第三场题解
    [深入浅出AutoSAR] SWC 设计与应用
    SpringBoot自带模板引擎Thymeleaf使用详解②
    流量传感器原理介绍
  • 原文地址:https://blog.csdn.net/HeyVIrBbox/article/details/127550004