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 源码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值