当前位置: 首页 > article >正文

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

第一章:数据自动管理

  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: root
        password: root
        url: jdbc:mysql://localhost:3306/boot_demo
        driver-class-name: com.mysql.jdbc.Driver
        type: com.zaxxer.hikari.HikariDataSource
    1. 在默认情况下,数据链接可以使用 DataSource 池进行自动配置
    2. Hikari 可用,SpringBoot 将使用它
    3. Commons DBCP2 可用,我们将使用它 
    4. 也可以指定数据源配置,通过 type 来选取使用哪种数据源
      spring:
        datasource:
          username: root
          password: root
          url: jdbc:mysql://localhost:3306/boot_demo
          driver-class-name: com.mysql.jdbc.Driver
          type: 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: root
          password: root
          url: jdbc:mysql://localhost:3306/boot_demo
          driver-class-name: com.mysql.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource
          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,wall,log4j
          maxPoolPreparedStatementPerConnectionSize: 20
          useGlobalDataSourceStat: true
          connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    3. 创建数据源注册类:
      @Configuration
      public class DruidConfig {
          @ConstructorProperties(prefix="spring.datasource")
          @Bean
          public DataSource dataSource(){
              return new DruidDataSource;
          }
      }
    4. 配置 druid 运行期监控
      @Configuration
      public class DruidConfig {
          @ConstructorProperties(prefix="spring.datasource")
          @Bean
          public DataSource dataSource(){
              return new DruidDataSource;
          }
      
          @Bean
          public 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
          @Bean
          public 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:
    public class TestController {
    
        @Autowired
        JdbcTemplate 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 的自动配置
    org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
  5. jdbcTemplateAutoConfiguration 源码:

http://www.kler.cn/a/529461.html

相关文章:

  • C#接口(Interface)
  • pytorch实现主成分分析 (PCA):用于数据降维和特征提取
  • 如何获取当前的位置信息
  • 19.Word:小马-校园科技文化节❗【36】
  • 单机伪分布Hadoop详细配置
  • 探索AI(chatgpt、文心一言、kimi等)提示词的奥秘
  • 游戏引擎 Unity - Unity 设置为简体中文、Unity 创建项目
  • 数据分析系列--[11] RapidMiner,K-Means聚类分析(含数据集)
  • 洛谷P1403 [AHOI2005] 约数研究
  • 构建医疗AI编程可控价值观罗盘:多维度融合导向
  • FIR滤波器:窗函数法
  • 医学图像分割任务的测试代码
  • C语言中的线程本地变量
  • 无用知识之:std::initializer_list的秘密
  • 【Java源码】基于SpringBoot+小程序的电影购票选座系统
  • vue入门到实战 二
  • 实战技巧:如何快速提高网站收录的多样性?
  • Baklib在企业知识管理领域的领先地位与三款竞品的深度剖析
  • 函数与递归
  • vue2和vue3路由封装及区别
  • 蛇年说蛇,革旧图新
  • VSCode插件HTML CSS Support
  • MyBatis-Plus笔记-快速入门
  • 于动态规划的启幕之章,借 C++ 笔触绘就算法新篇
  • 深度学习模型在汽车自动驾驶领域的应用
  • 二叉树——429,515,116