java study notes-Mybatis-Plus

Mybatis-Plus

Mybatis-Plus is an enhancement tool for Mybatis. On the basis of Mybatis, only enhancements are made without changes . It was born to simplify development and improve efficiency .

img

characteristic

Important note: MP is suitable for single-table operations , if you encounter multiple-table operations , hand-written SQL will be more efficient

  • No intrusion : only enhance and do not change, the introduction of it will not affect the existing project, it is as smooth as silk
  • Low loss : basic CURD will be automatically injected at startup, performance is basically no loss, direct object-oriented operation
  • Powerful CRUD operations : built-in general Mapper, general service, only a small amount of configuration can realize most of the CRUD operations of a single table, and a more powerful condition builder to meet various usage requirements
  • Support Lambda form call : through Lambda expressions, you can easily write all kinds of query conditions, no need to worry about writing wrong fields
  • Supports automatic primary key generation : supports up to 4 primary key strategies (including a distributed unique ID generator-Sequence), which can be configured freely, which perfectly solves the primary key problem
  • Support ActiveRecord mode : Support ActiveRecord form call, entity classes only need to inherit Model class to perform powerful CRUD operations
  • Support custom global general operations : support global general method injection (Write once, use anywhere)
  • Built-in code generator : Use code or Maven plug-in to quickly generate Mapper, Model, Service, Controller layer code, support template engine, and more custom configurations for you to use
  • Built-in paging plug-in : Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
  • Paging plugin supports multiple databases : supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
  • Built-in performance analysis plug-in : Sql statement and its execution time can be output. It is recommended to enable this function during development and testing to quickly detect slow queries
  • Built-in global interception plug-in : Provides intelligent analysis and blocking of delete and update operations of the entire table, and can also customize interception rules to prevent misoperations

MP entry case

Precautions

1. Edit the pojo to add the annotation @tableName @tableId
2. Implement the interface to inherit from BaseMapper
3. Edit the YML file configuration information to change mybatis to mybatis-plus

Import the jar package

Note: Because MP is internally compatible with Mybatis, the original Mybatis dependency package will be deleted after MP is introduced.

Delete the dependency package of mybatis

<!--spring整合mybatis  暂时  -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

Import MP's dependency package

  <!--spring整合mybatis-plus  -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis0plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>

Object to table mapping

Insert picture description here

Inherit the public Mapper interface

Insert picture description here

Modify YML configuration file

Note: springBoot should be converted from the original Mybatis database connection to the MP database connection

[External link image transfer failed. The source site may have an anti-hotlinking mechanism. It is recommended to save the image and upload it directly (img-hRy9ylT6-1622599384584)(C:\Users\MTA\AppData\Roaming\Typora\typora-user-images\ image-20210528113405293.png)]

Edit MP entry case

Compare the difference between Sql writing/MP writing...

@SpringBootTest
public class TestMybatis {
    // sprign容器 <userMapper,代理对象>
    // 面向接口编程 扩展性好
    @Autowired
    private UserMapper userMapper;//JDK动态代理

    //报错说明:com.jt.mapper.UserMapper.findAll  不匹配!!!!
    //关于测试类代码说明: 要求: public   返回值void  方法名称不能叫test
    @Test
    public void test01(){
        System.out.println(userMapper.getClass());
        List<User> userList = userMapper.findAll();   //接口的方法  数据库只能识别Sql语句
        System.out.println(userList);
    }

    //查询 用户的全部记录 面向对象的方式操作数据库.
    //只能用于单表查询
    @Test
    public void testFind(){
        //暂时不需要任何where条件  查询的是全部记录.
        List<User> userList = userMapper.selectList(null);
        System.out.println(userList);
    }
}

Mybatis CURD operation practice

Edit test code

  @Test
    public void insert(){
        User user = new User();
        user.setName("星期五").setAge(18).setSex("男");
        userMapper.insertUser(user);
        System.out.println("新增用户成功");
    }

    //根据name="星期五",将name="星期六"
    @Test
    public void update(){
        String oldName = "星期五";
        String newName = "星期六";
        userMapper.updateByName(oldName,newName);
        System.out.println("更新用户成功");
    }

    //删除用户信息 根据name属性删除数据
    @Test
    public void delete(){
        String name = "星期六";
        userMapper.deleteByName(name);
        System.out.println("删除用户成功");
    }

Edit Mapper interface

@Insert("insert into demo_user(id,name,age,sex) " +
            "value (null,#{name},#{age},#{sex})")
    void insertUser(User user);
    @Update("update demo_user set name = #{newName} where name=#{oldName}")
    void updateByName(String oldName, String newName);
    //Mybatis中如果传递的参数只有一个,则名称任意 一般不用.
    @Delete("delete from demo_user where name=#{name}")
    void deleteByName(String name);

How MP works

1) One-to-one mapping between objects and tables through annotations

2) Realize one-to-one mapping between the attributes of the object and the fields in the table through attribute annotations

3) Extract public methods into the BaseMapper interface

4) Convert the method object operated by the user into a SQL statement that the database can recognize

demo1: userMapper.insert (user object)

SQL1: insert into table name (field name...) value (attribute value...)

Splicing process:

insert into table name (field name...) value (attribute value...)

1) Find the parent interface BaseMapper through userMapper

2) Find the generic object User object according to BaseMapper

3) Find the specified annotation @TableName according to the user object to obtain the table name

4) Dynamically obtain the fields in the table @TableField according to the user object

5) Get the value of the attribute while getting the field, and finally perform SQL splicing

6) MP sends the spliced ​​SQL to the Mybaits framework for processing and execution

insert into demo|_user(id,name…) value(value1,value2…)

MP practice

Query by ID

 /**
     * 1.根据Id=23数据
     */
    @Test
    public void select01(){
       User user = userMapper.selectById(23);
       System.out.println(user);
    }

Object query

Configuration log

Insert picture description here
 /**
     * 查询 name="潘凤"  sex="男"
     * 结果: 1项 userMapper.selectOne()
     *      多项 userMapper.selectList()
     * Sql: where name="xxx" and sex="xxx"
     * queryWrapper: 条件构造器  拼接where条件
     * 如果遇到多条件查询,则默认的连接符and
     * 方式1: 可以通过对象的方式进行控制
     */
    @Test
    public void select02(){
        User user = new User();
        user.setName("潘凤").setSex("男");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

Special character practice

 /**
     * 要求: age>18岁  or sex=男的用户
     * 转义字符:   > gt,   < lt , = eq
     *            >= ge , <= le
     */
    @Test
    public void select03(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //编辑的是数据库字段信息
        queryWrapper.gt("age", 18)
                    .or()
                    .eq("sex","男");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

linke keyword

 /**
     * 要求: 查询name中包含"精" 并且按照age 降序排列
     * Sql: like "%精%"  包含精
     *      like "精%"   以精开头
     *      like "%精"   以精结尾
     */
    @Test
    public void select04(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name","精")
                    .orderByDesc("age");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

In keyword

 /**
     * 要求: 查询name中包含"精" 并且按照age 降序排列
     * Sql: like "%精%"  包含精
     *      like "精%"   以精开头
     *      like "%精"   以精结尾
     */
    @Test
    public void select04(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name","精")
                    .orderByDesc("age");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

Not for Null query

 /**
     * 要求: 查询name中包含"精" 并且按照age 降序排列
     * Sql: like "%精%"  包含精
     *      like "精%"   以精开头
     *      like "%精"   以精结尾
     */
    @Test
    public void select04(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name","精")
                    .orderByDesc("age");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

Dynamic SQL statement query

 /**
     * 要求: 查询name中包含"精" 并且按照age 降序排列
     * Sql: like "%精%"  包含精
     *      like "精%"   以精开头
     *      like "%精"   以精结尾
     */
    @Test
    public void select04(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name","精")
                    .orderByDesc("age");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

Select field query

 /**
     * 要求: 查询name中包含"精" 并且按照age 降序排列
     * Sql: like "%精%"  包含精
     *      like "精%"   以精开头
     *      like "%精"   以精结尾
     */
    @Test
    public void select04(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("name","精")
                    .orderByDesc("age");
        //根据对象中不为null的属性 拼接where条件
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

MP update operation

Update operation

@SpringBootTest
public class TestMP2 {

    @Autowired
    private UserMapper userMapper;

    /**
     * 将ID=229的用户名称 改为六一儿童节
     */
    @Test
    public void updateUser(){
        User user =  new User();
        user.setId(229).setName("六一儿童节");
        //set name="xxx" where id = 229
        userMapper.updateById(user);
    }

    /**
     * 更新操作2
     *      将name="六一儿童节" 改为"端午节"
     *  参数说明:
     *         1.实体对象  封装修改后的数据 set结构
     *         2.UpdateWrapper 修改的条件构造器
     *  Sql: update demo_user set name="端午节" where name="61"
     */
    @Test
    public void updateUser2(){
        User user = new User();
        user.setName("端午节");
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("name", "六一儿童节");
        userMapper.update(user,updateWrapper);
    }
}