Spring Boot Learning (31): SpringBoot integra MyBatis-Plus, ¡versión mejorada de MyBatis!

Prefacio

Serie Spring Boot: Haga clic para ver los artículos de la serie Spring Boot


MyBatis-Plus

MyBatis-Plus (MP para abreviar) es una herramienta de mejora para MyBatis. Sobre la base de MyBatis, solo mejora y no cambia. Nace para simplificar el desarrollo y mejorar la eficiencia.

característica


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

Marco de referencia

Inserte la descripción de la imagen aquí
Una breve introducción a MyBatis-Plus, luego comience a integrar MyBatis-Plus


SpringBoot integra MyBatis-Plus

1. Agregar dependencias

La versión MyBatis-Plus 3.0 se basa en JDK8

Mybatis-plus depende de lo siguiente, la última versión es 3.4.1, puede elegir la versión usted mismo

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

La siguiente es la información de versión de la que depende MP

Inserte la descripción de la imagen aquí
Nota: ¡Intente no importar las dependencias mybatis y mybatis-plus al mismo tiempo! Evite las diferencias de versión que causan problemas impredecibles.

2. Configurar la conexión a la base de datos

Agregue la configuración de la base de datos en application.properties, de la siguiente manera

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

La siguiente configuración es para imprimir la instrucción sql ejecutada en la consola. Si desea generar sql en la consola, puede agregar la siguiente configuración para facilitar las pruebas

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

3. Agregue la anotación @MapperScan a la clase de inicio Spring Boot para escanear la carpeta Mapper

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

    public static void main(String[] args) {
    
    


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

}

Después de la configuración anterior, podemos usar MP. De hecho, también podemos encontrar que la configuración es básicamente la misma que la configuración de mybatis. Esto se debe a que MP se ha mejorado originalmente sobre la base de mybatis. Conserva las funciones de mybatis y es utilizado en mybatis. Proporciona funciones más mejoradas

CRUD de MyBatis-Plus

A continuación, demostraré la función de crud simple de MyBatis-Plus

1. Crea una clase de entidad

@Data
public class User {
    
    

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

2. Cree una interfaz de mapeador. La interfaz de mapeador hereda BaseMapper. Después de que Mapper hereda la interfaz de BaseMapper, puede obtener la función CRUD sin escribir el archivo mapper.xml, es decir, el método definido en BaseMapper

A continuación se muestra mi propio mapeador

@Repository
public interface UserMapper extends BaseMapper<User> {
    
    

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

Nota: mybatis-plus admite la función de mybatis, por lo que también podemos usar archivos de anotación sql y xml

Por cierto, mybatis-plus está escrito en chino, por lo que los comentarios del código fuente también son chinos, lo cual es muy amigable.

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

Además de heredar BaseMapper, en MP, también puede obtener funciones CRUD básicas heredando ServiceImpl. ServiceImpl se define de la siguiente manera


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

lograr


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

Nota: Dos tipos genéricos de ServiceImpl, M representa una clase que hereda BaseMapper y T representa una clase de entidad

prueba

A continuación, probaremos la función de 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);

    }

}

La integración de MyBatis-Plus es tan simple que se introducirán más operaciones en detalle más adelante

Supongo que te gusta

Origin blog.csdn.net/qq_36551991/article/details/113120152
Recomendado
Clasificación