SoFunction
Updated on 2025-05-22

Summary of the basic usage of MyBatis-Flex BaseMapper interface

A brief introduction to MyBatis-Flex

MyBatis-Flex is an elegant MyBatis enhancement framework that is very lightweight and has extremely high performance and flexibility. We can easily link any database with Mybaits-Flex, and its built-in QueryWrapper^ highlights help us greatly reduce the possibility of errors while writing SQL.

All in all, MyBatis-Flex can greatly improve our development efficiency and development experience, giving us more time to focus on our own affairs.

characteristic

1. Lightweight

Apart from MyBatis, there are no third-party dependencies and no interceptors. The principle is a light implementation implemented through SqlProvider. At the same time, during the execution process, no Sql parsing (Parse) is run lightly. This brings several benefits: 1. Extremely high performance; 2. Extremely easy to track and debug code; 3. Higher control.

2. Flexible

While supporting Entity's addition, deletion, modification and query, and pagination query, MyBatis-Flex provides Db + Row^ flexible tools, which can add, deletion, modification and query the database and pagination query without the need for entity classes. At the same time, the built-in QueryWrapper^ of MyBatis-Flex can easily help us realize it.Multi-table queryLink querySubqueryand other common SQL scenarios.

3. Powerful

Supports any relational database, and can also be continuously expanded through dialects, and supportsMultiple (composite) primary keyLogical deletionOptimistic lock configurationData desensitizationData Audit、 Data fillingand other functions.

Basic Methods

INSERT

The BaseMapper interface provides insert and insertBatch methods for adding new data.

  • insert(entity): Insert entity class data without ignoring the null value.
  • insertSelective(entity): Insert entity class data, but ignore null data and insert only content with value. The advantage of this is that the database has configured some default values ​​so that these default values ​​will take effect.
  • insert(entity, ignoreNulls): Insert entity class data.
  • insertWithPk(entity): Insert the entity class with the primary key, and do not ignore the null value.
  • insertSelectiveWithPk(entity): Insert the entity class with the primary key, ignore the null value.
  • insertWithPk(entity, ignoreNulls): Insert with primary key, at this time the entity class will not generate primary keys through the primary key generator.
  • insertBatch(entities): Insert entity class data in batches, only the inserted field content will be constructed based on the first piece of data.
  • insertBatch(entities, size): Insert entity class data in batches and divide it by size.
  • insertOrUpdate(entity): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert, insert or update will not ignore the null value.
  • insertOrUpdateSelective(entity): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert, insert or update will ignore the null value.
  • insertOrUpdate(entity, ignoreNulls): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert it.

① insert

    /**
      * insert(entity): Insert entity class data, not ignoring the null value.
      * insert(entity, ignoreNulls): Insert entity class data.
      */
    @Test
    public void testInsert() {
        /**
          * The null value is not ignored by default
          * INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?)
          */
        int row = (new Account().setUserName(null).setBirthday(new Date()).setAge(25));
        (row, 1);

        /**
          * ignoreNulls true: ignore null, false: do not ignore null
          * INSERT INTO `tb_account`(`user_name`) VALUES (?)
          */
        int row2 = (new Account().setUserName("ly3").setBirthday(null).setAge(null), true);
        (row2, 1);
    }

② insertSelective 

    /**
      * insertSelective(entity): Insert entity class data, but ignore null data and insert only valued content.  The advantage of this is that the database has configured some default values ​​so that these default values ​​will take effect.
      */
    @Test
    public void testInsertSelective() {
        /**
         * INSERT INTO `tb_account`(`user_name`) VALUES (?)
         */
        int row = (new Account().setUserName("Chen Yuanhang").setAge(null));
        (row, 1);
    }

③ insertWithPk 

    /**
      * insertWithPk(entity): Insert the entity class with the primary key, and do not ignore the null value.
      */
    @Test
    public void testInsertWithPk() {
        /**
         * INSERT INTO `tb_account`(`id`, `user_name`, `age`, `birthday`) VALUES (?, ?, ?, ?)
         */
        int row = (new Account().setUserName("Liao Kairui").setId(5L).setBirthday(null));
        (row, 1);
    }

④ insertBatch 

    /**
      * insertBatch(entities): Insert entity class data in batches, only the inserted field content will be constructed based on the first piece of data.
      * insertBatch(entities, size): Insert entity class data in batches and divide it by size.
      */
    @Test
    public void testInsertBatch() {
        List<Account> accounts = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            Account account = new Account().setUserName("ly" + i).setBirthday(new Date()).setAge(20 + i);
            (account);
        }
        /**
          * Batch insert, you can specify the data size of each insert
          * size=2 : INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?), (?, ?, ?)
          * size=3 : INSERT INTO `tb_account`(`user_name`, `age`, `birthday`) VALUES (?, ?, ?), (?, ?, ?), (?, ?, ?)
          * ......
          */
        int rows = (accounts, 2);
        ("rows = " + rows);
    }

⑤ insertOrUpdate 

    /**
      * insertOrUpdate(entity): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert, insert or update will not ignore the null value.
      * insertOrUpdateSelective(entity): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert, insert or update will ignore the null value.
      * insertOrUpdate(entity, ignoreNulls): Insert or update. If the primary key has a value, update it. If there is no primary key value, insert it.
      */
    @Test
    public void testInsertOrUpdate() {
        Account account = new Account().setUserName("ly-update2").setId(3L).setBirthday(new Date()).setAge(21);
        /**
         * UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
         */
        int row = (account);
        (row, 0, 1);

        account = new Account().setUserName("ly-update2").setBirthday(null).setAge(21);
        /**
         * INSERT INTO `tb_account`(`user_name`, `age`) VALUES (?, ?)
         */
        int row2 = (account);
        (row2, 0, 1);
    }

DELETE

The BaseMapper interface provides deleteById, deleteBatchByIds, deleteByMap, deleteByQuery methods to delete data;

  • deleteById(id): delete data according to the primary key. If there are multiple primary keys, an array needs to be passed in, for example: new Integer[]{100,101}.
  • deleteBatchByIds(ids): batch delete data based on multiple primary keys.
  • deleteBatchByIds(ids, size): batch delete data based on multiple primary keys.
  • deleteByMap(whereConditions): deletes data according to the conditions built by Map.
  • deleteByCondition(whereConditions): delete data according to query conditions.
  • deleteByQuery(queryWrapper): deletes data according to query conditions.

① deleteById

    /**
      * deleteById(id): delete data according to the primary key.
      * ??? If there are multiple primary keys, an array needs to be passed, for example: new Integer[]{100,101}.  ??? Scepticism
      */
    @Test
    public void testDeleteById() {
        /**
         * DELETE FROM `tb_account` WHERE `id` = ?
         */
        int row = (9L);
        (row > 0);
    }

② deleteBatchByIds  

    /**
      * deleteBatchByIds(ids): batch delete data based on multiple primary keys.
      * deleteBatchByIds(ids, size): batch delete data according to multiple primary keys.
      */
    @Test
    public void testDeleteBatchByIds() {
        List<Integer> ids = (5, 6, 7, 8);
        /**
         * DELETE FROM `tb_account` WHERE `id` = ? OR `id` = ? OR `id` = ? OR `id` = ?
         */
        int rows = (ids);
        (rows > 0);

        /**
          * Delete in batches
          * size=2: DELETE FROM `tb_account` WHERE `id` = ? OR `id` = ?
          */
        int rows2 = (ids, 2);
        (rows2 > 0);
    }

③ deleteByMap 

    /**
      * deleteByMap(whereConditions): Delete data according to the conditions built by Map.
      */
    @Test
    public void testDeleteByMap() {
        /**
         * DELETE FROM `tb_account` WHERE `tb_account`.`age` = ?
         */
        int rows = (("age", 25));
        (rows > 0);
    }

④ deleteByCondition  

    /**
      * deleteByCondition(whereConditions): Delete data according to query conditions.
      */
    @Test
    public void testDeleteByCondition() {
        QueryCondition condition = ().and("age = 27");
        /**
         * DELETE FROM `tb_account` WHERE age = 27
         */
        int rows = (condition);
        (rows > 0);

        /**
         * DELETE FROM `tb_account` WHERE `id` > ?
         */
        int rows2 = ((35));
        (rows2 > 0);
    }

⑤ deleteByQuery

    /**
      * deleteByQuery(queryWrapper): deletes data according to query conditions.
      */
    @Test
    public void testDeleteByQuery() {
        /**
         * DELETE FROM `tb_account` WHERE `age` >= ?
         */
        QueryWrapper wrapper = ().where((32));
        int rows = (wrapper);
        (rows > 0);
    }

UPDATE

The BaseMapper interface provides update, updateByMap, updateByQuery methods to update data;

  • update(entity): Update data according to the primary key. If the entity class attribute data is null, the attribute will not be new to the database.
  • update(entity, ignoreNulls): update data to the database according to the primary key.
  • updateByMap(entity, whereConditions): Update data according to the conditions built by Map.
  • updateByMap(entity, ignoreNulls, whereConditions): Update data according to the conditions built by Map.
  • updateByCondition(entity, whereConditions): Update data according to query conditions.
  • updateByCondition(entity, ignoreNulls, whereConditions): Update data according to query conditions.
  • updateByQuery(entity, queryWrapper): update data according to query conditions.
  • updateByQuery(entity, ignoreNulls, queryWrapper): update data according to query conditions.

① update 

    @Test
    public void testUpdate() {
        Account account = new Account().setId(5L)
                .setAge(39)
                .setUserName("Test Modification")
                .setBirthday(new Date(2023, , 6, 12, 12, 12));
        /**
         * UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
         */
        int rows = (account);
        (rows > 0);
    }
	
    @Test
    public void testUpdateIgnoreNulls() {
        Account account = new Account().setId(6L)
                .setAge(null)
                .setUserName(null)
                .setBirthday(new Date(2023, , 6, 12, 12, 12));
        /**
          * Do not ignore null values
          * UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
          */
        int rows = (account, false);
        ("rows = " + rows);
    }

② updateByMap 

    @Test
    public void testUpdateByMap() {
        Account account = new Account()
                .setId(7L) // Not effective                .setUserName("updateByMap")
                .setAge(24)
                .setBirthday(null);
        // Note: This way, updating the id of the entity class will not take effect        Map<String, Object> whereCondition = ("id", 13);

        /**
          * Ignore null
          * UPDATE `tb_account` SET `user_name` = ? , `age` = ? WHERE `id` = ?
          */
        (account, whereCondition);

        /**
          * Do not ignore null
          * UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
          */
        (account, false, whereCondition);
    }

③ updateByCondition 

    /**
      * updateByCondition(entity, whereConditions): Update data according to query conditions.
      * updateByCondition(entity, ignoreNulls, whereConditions): Update data according to query conditions.
      */
    @Test
    public void testUpdateByCondition() {
        Account account = new Account()
                .setId(8L)
                .setUserName("updateByCondition")
                .setBirthday((()));
        QueryCondition condition = (new QueryColumn("id"),
                , 8);
        /**
          * Ignore null
          * UPDATE `tb_account` SET `user_name` = ? , `birthday` = ? WHERE `id` = ?
          */
        (account, condition);

        /**
          * Do not ignore null
          * UPDATE `tb_account` SET `user_name` = ? , `age` = ? , `birthday` = ? WHERE `id` = ?
          */
        (account, false, condition);
    }

④ updateByQuery

    /**
      * updateByQuery(entity, queryWrapper): Update data according to query conditions.
      * updateByQuery(entity, ignoreNulls, queryWrapper): Update data according to query conditions.
      */
    @Test
    public void testUpdateByQuery() {
        Account account = new Account().setUserName("updateByQuery");

        /**
         * UPDATE `tb_account` SET `user_name` = ? WHERE `id` = ?
         */
        (account,
                ().where((9L)));
    }

⑤ UpdateEntity partial fields are updated

    @Test
    public void testUpdateEntity1() {
        Account account = (, 10L);
        /**
          * Official description: Objects created through UpdateEntity will only update the fields that call the setter method. If the setter method is not called, no matter what the value of the attribute in this object is, it will not be updated to the database.
          */
        (66)
                .setUserName("UpdateEntity")
                .setBirthday(null);
        (account);
    }

    @Test
    public void testUpdateEntity2() {
        Account account = new Account()
                .setId(10L)
                .setUserName("UpdateEntity2");
        UpdateWrapper wrapper = (account);
        // (, (1));

        ("age", "age + 1");
        (account);
    }

    @Test
    public void testUpdateEntity3() {
        Account account = new Account()
                .setId(10L)
                .setUserName("UpdateEntity2");
        UpdateWrapper wrapper = (account);

        // (, (1));

        (, "select * from t_account where id = 3");
        // (account, wrapper);
    }

⑥ UpdateChain

    @Test
    public void testUpdateChain() {
        /**
         * UPDATE `tb_account` SET `birthday` = ? , `age` = age + 1 WHERE `age` = ?
         */
        ()
                .set(Account::getBirthday, new Date())
                .setRaw(Account::getAge, "age + 1")
                .where((11)).update();
    }

The difference between set() and setRaw()In Row, UpdateWrapper, and UpdateChain, two methods set() and setRaw() are provided for setting data. So, what's the difference?

  • The set() method is used to set parameter data.
  • setRaw() is used to set SQL stitching data.

For example,

//Update data()
	.set(Account::getAge, (1))
	.where(Account::getId).ge(100)
	.and(Account::getAge).eq(18)
	.update();

Update() is performed through UpdateChain, and the SQL it executes is as follows:

UPDATE `tb_account` SET `age` = `age` + 1
WHERE  `id` >= 100 AND `age` = 18

This is the article about the basic usage of MyBatis-Flex BaseMapper interface. For more information about MyBatis-Flex BaseMapper interface usage, please search for my previous articles or continue browsing the related articles below. I hope you will support me more in the future!