Spring Boot学习(三十一):SpringBoot集成MyBatis-Plus,增强版MyBatis!

前言

Spring Boot系列: 点击查看Spring Boot系列文章


MyBatis-Plus

MyBatis-Plus(简称 MP)是一个 MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特性


 - 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
 
 - 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
 
 - 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD
   操作,更有强大的条件构造器,满足各类使用需求
 
 - 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错

 - 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
 
 - 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD
   操作 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
 
 - 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller
   层代码,支持模板引擎,更有超多自定义配置等您来使用
 
 - 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询

 - 分页插件支持多种数据库:支持
   MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库

 - 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询

 - 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

框架结构

在这里插入图片描述
简单介绍了MyBatis-Plus,下面就开始集成MyBatis-Plus


SpringBoot集成MyBatis-Plus

1、添加依赖

MyBatis-Plus 3.0 版本基于 JDK8

mybatis-plus 依赖如下,现在最新的版本为3.4.1,大家自行选择版本

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

<!-- 数据库驱动 ,根据自己的数据库选择对应的驱动,我这里是mysql的驱动-->
<dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
</dependency>

下面是MP依赖的版本信息

在这里插入图片描述
注意:尽量不要同时导入 mybatis 和 mybatis-plus依赖!避免版本的差异造成无法预知的问题。

2、配置数据库连接

在application.properties中添加数据库的配置,如下

#数据库url
spring.datasource.url=jdbc:mysql://192.168.91.128:3306/mytest?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
# 驱动版本不同,对应的driver-class-name不同
# mysql 5  com.mysql.jdbc.Driver
# mysql 8  com.mysql.cj.jdbc.Driver、在datasource.url需要增加时区的配置serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
#数据库用户名
spring.datasource.username=root
#密码
spring.datasource.password=root

下面配置为在控制台打印执行的sql语句,如果你想在控制台输出sql的话可以加上下面配置,便于测试

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

3、在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹

@SpringBootApplication
@MapperScan("com.example.spring_cloud_demo.mapper")
public class SpringCloudDemoApplication {
    
    

    public static void main(String[] args) {
    
    


        SpringApplication.run(SpringCloudDemoApplication.class, args);
    }

}

经过上面的配置,我们就可以使用MP了,其实我们也可以发现配置和mybatis配置是基本一样的,这是因为MP本就是在mybatis的基础上进行增强,它保留了mybatis的功能,并在mybatis的功能上提供了更多的增强功能

MyBatis-Plus的CRUD

下面我就演示下MyBatis-Plus简单的crud功能

1、创建一个实体类

@Data
public class User {
    
    

    private Long id;
    
    private String name;
    
    private Integer age;
    
    private String email;
}

2、创建mapper接口,mapper接口继承BaseMapper,Mapper 继承BaseMapper接口后,无需编写 mapper.xml 文件,即可获得CRUD功能,即BaseMapper中定义好的方法

下面是我自己的mapper

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    

    @Select("select  * from user where id=#{id}")
    List<User>getUserList(@Param("id")Integer id);
    
}

注:mybatis-plus支持mybatis的功能,所以注解sql,xml文件我们同样可以使用

顺便提一下 mybatis-plus是中国人编写的,所以源码注释也是中文,很友好

BaseMapper源码如下:

/**
 * Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
 * <p>这个 Mapper 支持 id 泛型</p>
 *
 * @author hubin
 * @since 2016-01-23
 */
public interface BaseMapper<T> extends Mapper<T> {
    
    

    /**
     * 插入一条记录
     *
     * @param entity 实体对象
     */
    int insert(T entity);

    /**
     * 根据 ID 删除
     *
     * @param id 主键ID
     */
    int deleteById(Serializable id);

    /**
     * 根据 columnMap 条件,删除记录
     *
     * @param columnMap 表字段 map 对象
     */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,删除记录
     *
     * @param wrapper 实体对象封装操作类(可以为 null)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

    /**
     * 删除(根据ID 批量删除)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 根据 ID 修改
     *
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

    /**
     * 根据 whereEntity 条件,更新记录
     *
     * @param entity        实体对象 (set 条件值,可以为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    /**
     * 根据 ID 查询
     *
     * @param id 主键ID
     */
    T selectById(Serializable id);

    /**
     * 查询(根据ID 批量查询)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 查询(根据 columnMap 条件)
     *
     * @param columnMap 表字段 map 对象
     */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询总记录数
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * <p>注意: 只返回第一个字段的值</p>
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     *
     * @param page         分页查询条件
     * @param queryWrapper 实体对象封装操作类
     */
    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

除了继承BaseMapper,在MP中,还可以通过继承ServiceImpl获取基本的CRUD功能,ServiceImpl定义如下


/**
 * IService 实现类( 泛型:M 是 mapper 对象,T 是实体 )
 *
 * @author hubin
 * @since 2018-06-23
 */
@SuppressWarnings("unchecked")
public class ServiceImpl<M extends BaseMapper<T>, T> implements IService<T> {
    
    
 
}

实现


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>  {
    
    
 
}

注意:ServiceImpl的两个泛型,M表示一个继承BaseMapper的类,T表示实体类

测试

下面,我们就来测试下BaseMapper的功能

@SpringBootTest
class SpringCloudDemoApplicationTests {
    
    

    private static Pattern linePattern = Pattern.compile("_(\\w)");

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testMP() {
    
    
        //插入
        User newUser = User.builder().id(3L).name("新增用户").age(22).email("666").build();
        userMapper.insert(newUser);


        //selectList() 方法的参数为 MP 内置的条件封装器 Wrapper,为null则表示没有条件,查询全部
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);


        //根据id查询
        User user = userMapper.selectById(2);

        //更新
        user.setName("hh");
        userMapper.updateById(user);

        System.out.println("-----------------------------");

        //QueryWrapper为对象封装操作类,主要用于构造查询条件
        QueryWrapper queryWrapper=new QueryWrapper();
        //ge方法用于构造大于等于条件,下面语句等于id>=2
        queryWrapper.ge(true,"id",2);
        List<User> userListByWrapper = userMapper.selectList(queryWrapper);
        userListByWrapper.forEach(System.out::println);

    }

}

MyBatis-Plus的集成就是这么简单,更多操作以后进行详细介绍

猜你喜欢

转载自blog.csdn.net/qq_36551991/article/details/113120152