Bootstrap

MybatisFoundation-SpringBoot

MybatisFoundation

一. 创建SpringBoot-Mybatis项目

  • SpringBoot 版本
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <spring-boot.version>2.5.0</spring-boot.version>
     </dependency>
    

1.1 添加依赖

1.1.1 mysql & mybatis 依赖

  • 版本
    <mysql.version>8.0.15</mysql.version>
    <mybatis-spring-boot-starter.version>2.2.2</mybatis-spring-boot-starter.version>
    
  • 依赖
            <!-- MySQL的依赖项 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- MyBatis整合Spring Boot的依赖项 -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>${mybatis-spring-boot-starter.version}</version>
            </dependency>
    
    

1.1.1 Druid连接池 依赖

  • 版本
    <druid-spring-boot.version>1.2.16</druid-spring-boot.version>
    
  • 依赖
            <!-- Druid数据库连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid-spring-boot.version}</version>
            </dependency>
    

1.2 编写配置文件

1.2.1 application.yml

  • yml
    #配置使用的配置文件
    spring.profiles.active: dev
    spring:
      # 配置连接池
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource #数据库连接池的类的全限定名
        druid:
          # 连接池初始化大小、最小空闲、最大并发连接数
          initial-size: 5
          min-idle: 5
          max-active: 20
          # 连接有效性检测配置
          test-on-borrow: true
          test-on-return: false
          test-while-idle: true
          validation-query: SELECT 1
          # 连接超时与回收策略配置
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 300000
          # 连接属性配置,包含连接超时、读取超时以及自动重连
          connection-properties: connectTimeout=30000;socketTimeout=30000;autoReconnect=true
          # 启用Druid的监控统计、防止SQL注入、日志记录等功能
          #filters: stat,wall,log4j
    
    mybatis:
      type-aliases-package: annotation.pojo # pojo 包简写
      mapper-locations: classpath:/mappers/*.xml # mybatis 映射的配置文件
      configuration:
        map-underscore-to-camel-case: true # 开启驼峰映射
    

1.2.2 application-dev.yml

  • yml
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
        username: root
        password: root
    
    logging:  # 日志级别
      level:
        com.baidu: debug  # 配置到当前包  日志级别为 debug
    
    

1.3 编写mapper

  • 编写mapper
    @Mapper
    public interface AlbumMapper {
         
        @Insert("insert into  admUser (name) values(#{name})")
        void insert(String name);
    }
    

1.4 编写配置文件 mapper/AlbumMapper.xml

  • 编写配置文件AlbumMapper.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <!--mapper 映射类这儿 -->
    <mapper namespace="com.baidu.mapper.AlbumMapper">
    
    </mapper>
    

1.4.5 mybatis配置至此结束,以下配置MyBatis-plus

1.4.6 添加依赖

  • 版本
    <mybatis-plus-spring-boot.version>3.3.0</mybatis-plus-spring-boot.version>
    
  • 依赖
            <!-- Mybatis Plus整合Spring Boot的依赖项 -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus-spring-boot.version}</version>
            </dependency>
    

1.4.7 配置pojo

  • 配置映射表明
  • 配置映射id
    @Data
    @TableName("admUser") //指定数据库的表名为admUser
    public class User  implements Serializable {
         
        @TableId(value = "name",type = IdType.AUTO) //指定id为name  id自增
        String name;
    }
    

1.4.8 配置mapper 继承 BaseMapper

  • 继承 BaseMapper<pojo类的泛型>
    public interface AlbumMapper extends BaseMapper<User> {
         
    }
    

1.4.9 测试

  • 测试
    @SpringBootTest
    @Slf4j
    public class TestClass {
         
        @Resource(name="albumMapper")
        AlbumMapper albumMapper;
        @Test
        public void test01(){
         
            ArrayList<String> ls = new ArrayList<>();
            boolean zs = ls.add("zs");
            List<User> users = albumMapper.selectBatchIds(ls);
            log.debug(users.toString());
        }
    }
    

三. 连接池

3.1 关于数据库连接池

  • 数据库连接池的具体表现是javax.sql.DataSource类型的对象,它用于管理若干个数据库连接(Connection对象),当需要连接到数据库时,从DataSource中取出Connection对象即可!
  • 在绝大部分情况下,Spring Boot项目默认使用的是Hikari

四. 传参方式

4.1 Gitee仓库

  • https://gitee.com/code-ql/mybatis-foundation-spring-boot.git

4.1 sql 创建 user dept 表

  • 举例
    drop database if exists test;
    create database test charset = utf8;
    
    use test;
    
    create table user
    (
        id      int primary key auto_increment,
        name    varchar(30),
        age     int,
        dept_id int
    );
    
    insert into user (id, name, age, dept_id)
    values (1, '貂蝉', 18, 100),
           (2, '西施', 19, 200),
           (3, '王昭君', 20, 100);
    
    create table dept
    (
        dept_id   int primary key auto_increment,
        dept_name varchar(30)
    );
    
    insert into dept (dept_id, dept_name)
    values (100, '财务部'),
           (200, '销售部');
    
    

4.2 创建pojo

  • 举例
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @Accessors(chain = true)
    public class User implements Serializable {
         
        private Integer id;
        private String name;
        private Integer age;
    }
    

4.3 编写Mapper

  • 接口上添加@Mapper注解

4.3.1 无参数传递

  • 举例
    /*
        无参数传递
     */
    @Select("select id, name, age, dept_id from user")
    List<User> findAll();
    

4.3.2 单个参数可以不封装直接写

  • 举例
    /*
        单个参数可以不封装直接写
     */
    @Select("select id, name, age, dept_id from user where id=#{id}")
    User findUserById01(Integer id);
    

4.3.3 多个参数不封装 并且不加@Param注解

  • 举例
    /*
        多个参数不封装 并且不加@Param注解 则只能按照arg0 arg1  arg2 ... 如此获取参数(被当做一个数组传进来)
     */
    @Select("select id, name, age, dept_id from user where id=#{arg0} and name=#{arg1}")
    User findUserById02(Integer id,String name);
    

4.3.4 多个参数不封装 加@Param注解

  • 举例
    /*
        多个参数不封装 加注解 可以正常根据 @Param的参数 来取值
           加了这个注解就相当于map传参
           key : 为@Param的参数
           v : 为属性的值
     */
    @Select("select id, name, age, dept_id from user where id=#{id} and name=#{name}")
    User findUserById03(@Param("id") Integer id,@Param("name") String name);
    

4.3.5 map传参

  • 举例
    /*
        map传参
     */
    @Select("select id, name, age, dept_id from user where id=#{id} and name=#{name}")
    User findUserById04(Map<String,String> map);
    

4.3.6 pojo传参

  • 举例
    /*
        pojo传参
     */
    @Select("select id, name, age, dept_id from user where id=#{id} and name=#{name}")
    User findUserById05(User user);
    

4.4 编写测试类

  • 举例
    @SpringBootTest
    @Slf4j
    public class UserMapperTest {
         
        @Resource(name = "userMapper")
        private 
;