The general process of introducing MyBatisPlus in Spring Boot

table of Contents

I. Introduction:

Two, general CRUD

Three, the code generator

Four, related dependencies


I. Introduction:

Mybatis is still quite popular in the persistence layer framework, and general projects are based on ssm. Although mybatis can directly manipulate the database through SQL statements in xml, it is very flexible. However, since the operation must be performed through SQL statements, a lot of xml files must be written, which is very troublesome. mybatis-plus solves this problem very well.

Introduction to mybatis-plus.

Mybatis-Plus (MP for short) is an enhancement tool for Mybatis. On the basis of Mybatis, only enhancements are made without changes. It is born to simplify development and improve efficiency. This is the official definition. For more introduction and features of mybatis-plus, please refer to the official website of mybatis-plus. So how is it enhanced? In fact, it has already encapsulated some crud methods, we don't need to write xml anymore, just call these methods directly, just like JPA.

I have published many high-quality articles on mybatis. You can follow the WeChat public account Java backend and reply to 666 to download this Java technology stack document.

Today I will share with you a tutorial on using MyBatisPlus on the DAO layer.

Official API address: https://mp.baomidou.com/#/?id=%E7%AE%80%E4%BB%8B

Mybatis-PLus is an enhancement toolkit of Mybatis. It only enhances without making changes. It is born to simplify development and increase productivity.

image

image

Two, general CRUD

  • Pass this project (few tables, large amount of data, very suitable)

  • Found that MyBatisPlus is in single-meter CRUD

  • It has absolute advantages over the original MyBatis:

image

image

The relevant code of this article is listed below. Other codes such as Druid data source configuration, MyBatisPlus paging configuration, sql output configuration, can be viewed on github:

https://github.com/larger5/SpringBoot_MybatisPlus.git

image

image

@RunWith(SpringRunner.class)
@SpringBootTest
public class PlusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    /**
     * 1、增加 insert
     */
    @Test
    public void insertTest() {
        User user = new User();
        user.setUsername("绿茶");
        user.setPassword("lvcha");
        // 返回对数据库影响操作数:1
        Integer insert1 = userMapper.insert(user); // 非空属性才会出现在 sql 中
        // 可以立刻获取插入新记录的 id
        System.out.println(user.getId());
        // 同上
        Integer insert2 = userMapper.insertAllColumn(user); // 所有属性都会出现在 sql 中
        // 同上
        System.out.println(user.getId());
    }

    /**
     * 2、修改 update
     */
    @Test
    public void updateTest() {
        User user = new User();
        user.setId(45);
        user.setUsername("cun");
        //user.setPassword("666");
        // 返回对数据库影响操作数:1
        Integer integer1 = userMapper.updateById(user); // 属性空则不修改
        System.out.println(integer1);
        // 同上
        Integer integer2 = userMapper.updateAllColumnById(user); // 属性空则字段空
        System.out.println(integer2);
    }

    /**
     * 3、查询 select
     */
    @Test
    public void selectTest() {
        // 根据id 查询一条记录
        User user = userMapper.selectById(46);
        System.out.println(user.getUsername());

        ArrayList<Integer> idList = new ArrayList<>();
        idList.add(61);
        idList.add(63);
        // 根据多个id 批量查询
        List<User> users = userMapper.selectBatchIds(idList);
        System.out.println(users.get(0).getUsername() + users.get(1).getUsername());

        User user1 = new User();
        user1.setId(61);
        user1.setUsername("cun");
        // 根据多个条件返回一个对象,若有多个符合条件的记录则将报错
        User user2 = userMapper.selectOne(user1);
        System.out.println(user2.getPassword());

        // 根据多个条件返回对象组,注意Map 中的key 必须和数据库表字段一直
        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("username", "cun");
        List<User> users1 = userMapper.selectByMap(columnMap);
        System.out.println(users1.size());


    }

    /**
     * 4、删除 delete
     */
    @Test
    public void deleteTest() {
        // 根据一个id 删除,返回对数据库影响操作数:1
        Integer integer1 = userMapper.deleteById(65);// 根据id删除一条记录
        System.out.println(integer1);

        ArrayList<Integer> idList = new ArrayList<>(); // 根据id集合批量删除
        idList.add(64);
        idList.add(66);
        // 根据多个id 批量删除,返回对数据库影响操作数:2
        Integer integer2 = userMapper.deleteBatchIds(idList);
        System.out.println(integer2);

        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("username", "cun");
        // 根据多个条件删除,返回对数据库影响操作数
        Integer integer3 = userMapper.deleteByMap(columnMap);
        System.out.println(integer3);
    }

    /**
     * 5、伪分页(获取全部数据再分页)
     */
    @Test
    public void pageTest() {
        // 分页查询,注意如果设置了 PaginationInterceptor 分页插件则会报错,
        List<User> users2 = userMapper.selectPage(new Page<User>(1, 2), null); //当前页、每页大小
        System.out.println(users2.get(0).getUsername() + users2.get(1).getUsername());
        System.out.println(users2.size());
    }


    /**
     * 6、条件构造器
     */
    @Test
    public void wrapperTest(){
        List<User> users = userMapper.selectList(new EntityWrapper<User>()
                .eq("username", "linhongcun")
        );
        System.out.println(users.size());
    }

}

Three, the code generator

The above code is automatically written through the general Mapper layer of MyBatisPlsus, and the related business logic is written in the Service layer. In fact, the MyBatisPlus code generator is used to automatically generate the Entity, Dao, Service, and Controller layers!

We usually write related business logic in the Controller layer, and the method used is similar to that of Mapper.

public class MpG {
    public static void main(String[] args) {
        //1. 全局配置
        GlobalConfig config = new GlobalConfig();
        config.setActiveRecord(false) // 是否支持AR模式
                .setAuthor("RpringRoot") // 作者
                .setOutputDir("D:\\data\\mp") // 生成路径
                .setFileOverride(true) // 文件覆盖
                .setIdType(IdType.AUTO) // 主键策略
                .setServiceName("%sService") // 设置生成的service接口的名字的首字母是否为I
                // IUserService
                .setBaseResultMap(true)
                .setBaseColumnList(true);

        //2. 数据源配置
        DataSourceConfig dsConfig = new DataSourceConfig();
        dsConfig.setDbType(DbType.MYSQL) // 设置数据库类型
                .setDriverName("com.mysql.jdbc.Driver")
                .setUrl("jdbc:mysql://127.0.0.1:3306/testspring?useSSL=true&verifyServerCertificate=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8")
                .setUsername("root")
                .setPassword("123");

        //3. 策略配置
        StrategyConfig stConfig = new StrategyConfig();
        stConfig.setCapitalMode(true) //全局大写命名
                .setDbColumnUnderline(true) // 指定表名 字段名是否使用下划线
                .setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
                .setTablePrefix("tb_")
                .setInclude("tb_user"); // 生成的表

        //4. 包名策略配置
        PackageConfig pkConfig = new PackageConfig();
        pkConfig.setParent("com.cn.plus")
                .setMapper("mapper")
                .setService("service")
                .setController("controller")
                .setEntity("entity")
                .setXml("mapper");

        //5. 整合配置
        AutoGenerator ag = new AutoGenerator();
        ag.setGlobalConfig(config)
                .setDataSource(dsConfig)
                .setStrategy(stConfig)
                .setPackageInfo(pkConfig);

        //6. 执行
        ag.execute();
    }
}

Four, related dependencies

// 选择 freemarker 引擎,默认 Veloctiy
// mpg.setTemplateEngine(new FreemarkerTemplateEngine());
<!-- mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.3</version>
        </dependency>
        <!-- 代码生成器默认使用如下模版引擎 -->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>

Finally, everyone pays attention:

One of the drawbacks of using MyBatis is to rely on the use of a code generator, so that the logic is basically written in the controller layer instead of the service layer, which is out of date.

Guess you like

Origin blog.csdn.net/baidu_39322753/article/details/113123503