MybatisPlus笔记

1 .MyBatisPlus 介绍

     MyBatis-Plus(简称 MP),是一个 MyBatis 的增强工具包,只做增强不做改变.

    为简化开 发工作、提高生产率而生.

  1.2 代码及文档发布地址

      官方地址:  http://mp.baomidou.com
 
      代码发布地址:   Github: https://github.com/baomidou/mybatis-plus   

      Gitee:  https://gitee.com/baomidou/mybatis-plus

      文档发布地址:  http://mp.baomidou.com/#/?id=%E7%AE%80%E4%BB%8B

   1.3 前置知识

       在学习MP之前,需要掌握Mybatis,Spring,Maven.

2.MyBatisPlubs 引入

 2.1 导入jar包

<dependency>      
    <groupId>com.baomidou</groupId> 
    <artifactId>mybatis-plus</artifactId>      
    <version>2.3</version> 
</dependency> 

2.2 在application.xml中修改Mybatis自带的MybatisSqlSessionFactoryBean 为 MP自带的 MybatisSqlSessionFactoryBean

<bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"> 

3. 通用CURD

3.1 基础

1) 提出问题: 

假设我们已存在一张 tbl_employee 表,且已有对应的实体类 Employee,实现 tbl_employee 表的 CRUD 操作我们需要做什么呢?

2) 实现方式:

基于 Mybatis    需要编写 EmployeeMapper 接口,并手动编写 CRUD 方法  提供 EmployeeMapper.xml 映射文件,并手动编写每个方法对应的 SQL 语句.

基于 MP  只需要创建 EmployeeMapper 接口, 并继承 BaseMapper 接口.这就是使用 MP需要完成的所有操作,甚至不需要创建 SQL 映射文件。

public class EmployeeMapper extends BaseMapper<Employee>{
}

3.2 插入操作
1) Integer insert(T entity);

2) @TableName

3) 全局的 MP 配置: <property name="tablePrefix" value="tbl_"></property>

4) @TableField

5) 全局的 MP 配置: <property name="dbColumnUnderline" value="true"></property>

6) @TableId

7) 全局的 MP 配置: <property name="idType" value="0"></property>

8) 支持主键自增的数据库插入数据获取主键值 Mybatis: 需要通过 useGeneratedKeys  以及  keyProperty 来设置 MP: 自动将主键值回写到实体类中

9) Integer  insertAllColumn(T entity)

3.3 更新操作
1) Integer updateById(T entity);

2) Integer updateAllColumnById( T entity)

3.4 查询操作
1) T selectById(Serializable id);

2) T selectOne( T entity);

3) List<T> selectBatchIds(List<? extends Serializable> idList);

4) List<T> selectByMap( Map<String, Object> columnMap);

5) List<T> selectPage(RowBounds rowBounds,  Wrapper<T> wrapper);

3.5 删除操作
1) Integer deleteById(Serializable id);

2) Integer deleteByMap( Map<String, Object> columnMap);

3) Integer deleteBatchIds(List< extends Serializable> idList);

3.6 通用 CRUD 小结
1) 以上是基本的 CRUD 操作,如您所见,我们仅仅需要继承一个 BaseMapper 即可实现 大部分单表 CRUD 操作。BaseMapper 提供了多达 17 个方法给大家使用, 可以极其方 便的实现单一、批量、分页等操作。极大的减少开发负担!

4.条件构造器 EntityWrapper

4.1 EntityWrapper 简介

1) Mybatis-Plus 通过 EntityWrapper(简称 EW,MP 封装的一个查询条件构造器)或者 Condition(与 EW 类似) 来让用户自由的构建查询条件,简单便捷,没有额外的负担, 能够有效提高开发效率

2) 实体包装器,主要用于处理 sql 拼接,排序,实体参数查询等

3) 注意: 使用的是数据库字段,不是 Java 属性!

4) 条件参数说明:


 
 4.2 举个栗子

List<Employee> userList = employeeMapper.selectPage(new Page<Employee>(2, 3), 
                         new EntityWrapper<Employee>()
                        .eq("last_name", "MybatisPlus")                   
                        .eq("gender", 1)                   
                        .between("age", 18, 50)   );

猜你喜欢

转载自blog.csdn.net/weixin_42236404/article/details/83751027