SpringBoot 整合 Mybatis:提升你的Java项目开发效率

news/2025/2/6 6:01:51/

第一章:数据自动管理

  1. 引入 JDBC 的依赖和 SpringBoot 的应用场景:
    <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId>
    </dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
    </dependency>
  2. 创建 application.yaml 进行配置:
    spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/boot_demodriver-class-name: com.mysql.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSource
    1. 在默认情况下,数据链接可以使用 DataSource 池进行自动配置
    2. Hikari 可用,SpringBoot 将使用它
    3. Commons DBCP2 可用,我们将使用它 
    4. 也可以指定数据源配置,通过 type 来选取使用哪种数据源
      spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/boot_demodriver-class-name: com.mysql.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSource# type: org.apache.commons.dbcp2.BasicDataSource
  3. 设置 druid 数据源:
    <dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version>
    </dependency>
    <dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.15</version>
    </dependency>
    1. 修改 application.yaml 文件中:
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    2. 在 application.yaml 文件中加入:
      spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/boot_demodriver-class-name: com.mysql.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: truefilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    3. 创建数据源注册类:
      java">@Configuration
      public class DruidConfig {@ConstructorProperties(prefix="spring.datasource")@Beanpublic DataSource dataSource(){return new DruidDataSource;}
      }
    4. 配置 druid 运行期监控
      java">@Configuration
      public class DruidConfig {@ConstructorProperties(prefix="spring.datasource")@Beanpublic DataSource dataSource(){return new DruidDataSource;}@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");Map<String,String> initParams = new HashMap<>();initParams.put("loginUsername","root");initParams.put("loginPassword","root");initParams.put("allow","");//默认就是允许所有访问initParams.put("deny","192.168.15.21");bean.setInitParameters(initParams);return bean;}//2、配置一个web监控的filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean;bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());Map<String,String> initParams = new HashMap<>();initParams.put("exclusions","*.js,*.css,/druid/*");bean.setInitParameters(initParams);bean.setUrlPatterns(Arrays.asList("/*"));return bean;}
      }
    5. 打开监控页面:http://localhost:8080/druid

第二章:SpringBoot 整合 JDBCTemplate

  1. 创建表:
    
    SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
    -- Table structure for tx_user
    -- ----------------------------
    DROP TABLE IF EXISTS `tx_user`;
    CREATE TABLE `tx_user` (`username` varchar(10) DEFAULT NULL,`userId` int(10) NOT NULL,`password` varchar(10) DEFAULT NULL,PRIMARY KEY (`userId`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  2. 创建 Controller:
    java">public class TestController {@AutowiredJdbcTemplate jdbcTemplate;@ResponseBody@RequestMapping("/query")public List<Map<String, Object>> query(){List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT * FROM tx_user");return maps;}
  3. 启动 SpringBoot 访问:http://localhost:8080/query
  4. SpringBoot 中提供了 jdbcTemplateAutoConfiguration 的自动配置
    java">org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
  5. jdbcTemplateAutoConfiguration 源码:

http://www.ppmy.cn/news/1569719.html

相关文章

React 中常见的Hooks,安排!

哈喽小伙伴们大家好&#xff01;我是小李&#xff0c;今天是年后开工的第一天&#xff0c;相信大家已经元气满满&#xff0c;准备好迎接新的一年的挑战了吧&#xff01;打起精神来&#xff0c;我们继续加油呀&#xff01;今天&#xff0c;给大家分享一道我之前面试被问到相关Ho…

deepseek、qwen等多种模型本地化部署

想要在本地部署deepseek、qwen等模型其实很简单,快跟着小编一起部署吧 1 环境搭建 1.1下载安装环境 首先我们需要搭建一个环境ollama,下载地址如下 :Ollama 点击Download 根据自己电脑的系统选择对应版本下载即可 1.2 安装环境(window为例) 可以直接点击安装包进行安…

Github 2025-02-02 php开源项目日报 Top10

根据Github Trendings的统计,今日(2025-02-02统计)共有10个项目上榜。根据开发语言中项目的数量,汇总情况如下: 开发语言项目数量PHP项目10Blade项目1Laravel:表达力和优雅的 Web 应用程序框架 创建周期:4631 天开发语言:PHP, BladeStar数量:75969 个Fork数量:24281 次…

IDA Pro的基础指南

引言 在网络安全和软件分析领域&#xff0c;逆向工程是理解程序行为、挖掘漏洞或分析恶意软件的核心技能之一。而IDA Pro&#xff08;Interactive Disassembler&#xff09;作为逆向工程的“瑞士军刀”&#xff0c;是每位安全研究员和分析师的必备工具。本文将带你从零开始&…

启元世界(Inspir.ai)技术浅析(二):深度强化学习

深度强化学习(Deep Reinforcement Learning, DRL)是启元世界在人工智能领域的一项核心技术,广泛应用于游戏AI、智能决策等领域。 一、状态(State) 1.1 概念与作用 **状态(State)**是指智能体对环境的感知,是智能体进行决策的基础。在深度强化学习中,状态通常是一个高…

计算图 Compute Graph 和自动求导 Autograd | PyTorch 深度学习实战

前一篇文章&#xff0c;Tensor 基本操作5 device 管理&#xff0c;使用 GPU 设备 | PyTorch 深度学习实战 本系列文章 GitHub Repo: https://github.com/hailiang-wang/pytorch-get-started PyTorch 计算图和 Autograd 微积分之于机器学习Computational Graphs 计算图Autograd…

信标链的基本概念

什么是信标链&#xff1f; 信标链&#xff08;Beacon Chain&#xff09;是以太坊网络从工作量证明&#xff08;PoW&#xff09;向权益证明&#xff08;PoS&#xff09;过渡过程中的一次关键升级&#xff0c;标志着区块链演进过程中的一个重要里程碑。信标链于2020年12月1日推出…

k8m 是一款轻量级、跨平台的 Kubernetes 仪表板

k8m 是一款轻量级、跨平台的 Kubernetes 仪表板&#xff0c;专注于简化集群管理与 AI 功能的集成。其最新版本 v0.0.28 于 2025 年 2 月 4 日发布&#xff0c;包含多项功能优化和安全增强。以下是该版本的核心更新内容&#xff1a; 1. 安全性与认证优化1 动态 JWT 密钥配置&…