当前位置 博文首页 > blackball1998的博客:整合Mybatis-Plus

    blackball1998的博客:整合Mybatis-Plus

    作者:[db:作者] 时间:2021-06-09 09:15

    整合Mybatis-Plus

    Mybatis-Plus是在Mybatis框架的基础上再次进行封装,从而增强了Mybatis的功能,他最核心的功能就是自动生成CURD语句,使我们不需要再去编写简单的Sql语句,只需要编写一些复杂的需要定制化的Sql语句,而且他还有很多实用的插件可以使用

    Mybatis-Plus也提供了Spring Boot的场景启动器,和Spring Boot的整合也很方便

    引入依赖

    首先需要引入Mybatis-Plus的启动器依赖

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.2</version>
    </dependency>
    

    需要注意的是,Mybatis-Plus的启动器依赖了Mybatis的核心依赖包,所以引入了Mybatis-Plus的启动器后不要再引入Mybaits的相关依赖

    设置配置

    设置Mybatis的配置使用mybatis-plus替代mybatis作为前缀,其属性跟mybatis下的属性是一样的

    mybatis-plus:
      configuration:
        cache-enabled: true
        lazy-loading-enabled: true
        map-underscore-to-camel-case: true
      type-aliases-package: com.blackball.entity
    

    mybatis-plus还为我们配置了默认的Sql映射文件的包扫描路径,默认值是classpath*:/mapper/**/*.xml

    自动生成Sql语句

    首先创建一个Mapper接口,然后继承BaseMapper类,设置泛型为对应的实体类

    @Mapper
    public interface UserMapper extends BaseMapper<User> {
    
    }
    

    测试之前我们打开mybatis-plus的Sql打印功能

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    

    测试接口

    @SpringBootTest
    class SpringDemoApplicationTests {
    
        @Autowired
        UserMapper userMapper;
    
        @Test
        void contextLoads() {
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    
    }
    

    测试结果如下

    在这里插入图片描述

    自动生成了Sql语句