Spring Boot learning (31): SpringBoot integrates MyBatis-Plus, enhanced version of MyBatis!

Preface

Spring Boot series: Click to view Spring Boot series articles


MyBatis-Plus

MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. On the basis of MyBatis, only enhancements are made without changes. It is born to simplify development and improve efficiency.

characteristic


 - 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
 
 - 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作

Framework

Insert picture description here
A brief introduction to MyBatis-Plus, then start to integrate MyBatis-Plus


SpringBoot integrates MyBatis-Plus

1. Add dependencies

MyBatis-Plus 3.0 version is based on JDK8

Mybatis-plus depends on the following, the latest version is 3.4.1, you can choose the version yourself

<!-- 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>

The following is the version information that MP depends on

Insert picture description here
Note: Try not to import mybatis and mybatis-plus dependencies at the same time! Avoid version differences causing unpredictable problems.

2. Configure database connection

Add the configuration of the database in application.properties, as follows

#数据库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

The following configuration is to print the executed sql statement in the console. If you want to output sql in the console, you can add the following configuration for easy testing

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

3. Add the @MapperScan annotation to the Spring Boot startup class to scan the Mapper folder

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

    public static void main(String[] args) {
    
    


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

}

After the above configuration, we can use MP. In fact, we can also find that the configuration is basically the same as the mybatis configuration. This is because MP is originally enhanced on the basis of mybatis. It retains the functions of mybatis and is used in mybatis. Provides more enhanced functions

CRUD of MyBatis-Plus

Below I will demonstrate the simple crud function of MyBatis-Plus

1. Create an entity class

@Data
public class User {
    
    

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

2. Create a mapper interface. The mapper interface inherits BaseMapper. After Mapper inherits the BaseMapper interface, you can get the CRUD function without writing the mapper.xml file, that is, the method defined in BaseMapper

Below is my own mapper

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    

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

Note: mybatis-plus supports the function of mybatis, so we can also use annotation sql and xml files

By the way, mybatis-plus is written by Chinese, so the source code comments are also Chinese, which is very friendly

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);
}

In addition to inheriting BaseMapper, in MP, you can also obtain basic CRUD functions by inheriting ServiceImpl. ServiceImpl is defined as follows


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

achieve


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

Note: Two generic types of ServiceImpl, M represents a class that inherits BaseMapper, and T represents an entity class

test

Next, we will test the function of 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);

    }

}

The integration of MyBatis-Plus is so simple, more operations will be introduced in detail later

Guess you like

Origin blog.csdn.net/qq_36551991/article/details/113120152