Aprendizagem do Spring Boot (31): O SpringBoot integra MyBatis-Plus, versão aprimorada do MyBatis!

Prefácio

Série Spring Boot: Clique para ver os artigos da série Spring Boot


MyBatis-Plus

O MyBatis-Plus (abreviatura de MP) é uma ferramenta de aprimoramento do MyBatis. Com base no MyBatis, ele apenas aprimora e não muda. Nasce para simplificar o desenvolvimento e melhorar a eficiência.

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 操作智能分析阻断,也可自定义拦截规则,预防误操作

Estrutura

Insira a descrição da imagem aqui
Uma breve introdução ao MyBatis-Plus, em seguida, comece a integrar o MyBatis-Plus


SpringBoot integra MyBatis-Plus

1. Adicionar dependências

A versão 3.0 do MyBatis-Plus é baseada em JDK8

Mybatis-plus depende do seguinte, a última versão é 3.4.1, você pode escolher a versão você mesmo

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

A seguir estão as informações da versão da qual o MP depende

Insira a descrição da imagem aqui
Nota: Tente não importar as dependências mybatis e mybatis-plus ao mesmo tempo! Evite diferenças de versão que causam problemas imprevisíveis.

2. Configure a conexão do banco de dados

Adicione a configuração do banco de dados em application.properties, como segue

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

A configuração a seguir é para imprimir a instrução sql executada no console. Se você deseja gerar sql no console, pode adicionar a seguinte configuração para facilitar o teste

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

3. Adicione a anotação @MapperScan à classe de inicialização Spring Boot para verificar a pasta Mapper

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

    public static void main(String[] args) {
    
    


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

}

Após a configuração acima, podemos usar MP. Na verdade, também podemos descobrir que a configuração é basicamente a mesma que a configuração mybatis. Isso ocorre porque MP é originalmente aprimorado com base em mybatis. Ele mantém as funções de mybatis e é usado em mybatis. Oferece funções mais aprimoradas

CRUD de MyBatis-Plus

Abaixo, demonstrarei a função simples e crud do MyBatis-Plus

1. Crie uma classe de entidade

@Data
public class User {
    
    

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

2. Crie uma interface do mapeador. A interface do mapeador herda o BaseMapper. Depois que o Mapper herda a interface do BaseMapper, você pode obter a função CRUD sem escrever o arquivo mapper.xml, ou seja, o método definido no BaseMapper

Abaixo está meu próprio 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 suporta a função de mybatis, então também podemos usar arquivos sql e xml de anotação

A propósito, mybatis-plus é escrito em chinês, então os comentários do código-fonte também são em chinês, o que é muito amigável

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

Além de herdar BaseMapper, no MP, você também pode obter funções CRUD básicas herdando ServiceImpl. ServiceImpl é definido como segue


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

alcançar


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

Nota: Dois tipos genéricos de ServiceImpl, M representa uma classe que herda BaseMapper e T representa uma classe de entidade

teste

A seguir, vamos testar a função do 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);

    }

}

A integração do MyBatis-Plus é tão simples, mais operações serão introduzidas em detalhes posteriormente

Acho que você gosta

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