SpringBoot整合Mybatis-plus 及代码生成器

本项目ORM框架

整合Mybatis-plus

  1. pmo.xml依赖导入
    • Mybatis-plus 最新版依赖
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.6</version>
    </dependency>
    
    • 测试依赖 用于单元测试

    使用 mybatis-plus新版提供的测试注解 @MybatisPlusTest

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter-test</artifactId>
        <version>3.5.6</version>
    </dependency>
    
    • 数据库连接依赖
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.26</version>
    </dependency>
    
  2. application.properties配置数据库连接
    spring.application.name=work02
    spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
    spring.datasource.username=developer-My
    spring.datasource.password=test
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    # MyBatis-Plus
    mybatis-plus.global-config.db-config.id-type=auto
    

新版代码生成器

Mybatis-plus逆向工程 根据数据库表生成 对应 controller entity service mapper及其映射

详细介绍演示 – Mybatis-plus官方文档

  1. 导入依赖
    <!--    逆向工程    -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.5.4</version>
    </dependency>
    
    <!-- freemarke 模板 -->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.28</version>
        <scope>compile</scope>
    </dependency>
    
    <!--   实体类ApiModel注解    -->
    <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.20</version>
    </dependency>
    
  2. 构建生成器
    public class CodeGenerator {
        public static void main(String[] args) {
            String url= "jdbc:mysql://localhost:3306/demo?userSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
            String username = "developer-My";
            String password = "test";
    
            // 获取当前用户的目录 
            String projectPath = System.getProperty("user.dir"); 
    
            // FastAutoGenerator 至少需要mybatis-plus-generator 3.5.4以上版本
            FastAutoGenerator.create(url, username, password)
                    .globalConfig(builder -> {
                        builder.author("cxcs")   // 设置作者
                                .enableSwagger() // 开启 swagger 模式
                                .fileOverride()   // 覆盖已生成文件
                                .outputDir(projectPath + "/work02/src/main/java"); // 指定输出目录
                    })
                    .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                        int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                        if (typeCode == Types.SMALLINT) {
                            // 自定义类型转换
                            return DbColumnType.INTEGER;
                        }
                        return typeRegistry.getColumnType(metaInfo);
    
                    }))
                    .packageConfig(builder -> {
                        builder.parent("com.example") // 设置父包名
                                .moduleName("work02") // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.xml, projectPath + "/work02/src/main/resources/mapper/")); // 设置mapperXml生成路径
                    })
                    .strategyConfig(builder -> {
                        builder.addInclude("user"); // 设置需要生成的表名
                        builder.addInclude("admin");
                        builder.addInclude("goods");
                        builder.addInclude("goods_type");
                        builder.addInclude("order_table");
                        builder.addInclude("orders_item");
                        builder.addInclude("cart_item");
                        builder.addInclude("address");
                    })
                    .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                    .execute();
        }
    }
    

在这里插入图片描述

运行出现的Bug

  1. 代码生成器 启动报错: 找不到类

在这里插入图片描述

查看官方文档, 发现依赖版本较低, 将 mybatis-plus-generator 依赖更新为 3.5.4 以上, 成功运行

  1. SpringBoot 整合Mybatis-plus后 启动报错

在这里插入图片描述

Error creating bean with name 'clientServiceImpl': Unsatisfied dependency expressed through field 'baseMapper': Error creating bean with name 'clientMapper' defined in file 
  • 发现扫描不到mapper层之后, 在 Application 启动类中添加注解

    @MapperScan("com.example.work02.mapper")
    
  • 添加后仍然报该错误

  • 注释部分依赖, 发现是 mybatis-plus-boot-starter-test 依赖的版本较低 3.4.2 更换为最新版 3.5.6

更换版本之后又出现另一个错误

Invalid value type for attribute 'factoryBeanObjectType': java.lang.String

在这里插入图片描述

  • 解决方案: 参考网址 – CSDN

  • 最后发现是 mybatis-plus-boot-starter-test 依赖包含的mybatis-spring版本较低

  • 需要手动升级依赖

  • <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.6</version>
        <exclusions>
            <exclusion>
                <artifactId>mybatis-spring</artifactId>
                <groupId>org.mybatis</groupId>
            </exclusion>
        </exclusions>
    </dependency>
    
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>3.0.3</version>
    </dependency>
    

单元测试

详细示例 – 官方文档

单元测试中对 Mybatis-plus 进行快速测试

@MybatisPlusTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class MybatisPlusSampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test  // 测试插入
    void testInsert() {
        User user = new User();
        user.setId(666);
        user.setUsername("zs");
        user.setPassword("1234");
        userMapper.insert(user);
        assertThat(user).isNotNull();
    }

    @Test   // 测试查询
    void testSelect() {
        List<User> user = userMapper.getAllNoTenant();
        System.out.println(user);
    }
}

在这里插入图片描述

前后端的交互

  1. 导入 json 依赖
<!--  JSON依赖  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
    <version>3.2.0</version>
</dependency>
  1. UserController.java
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserMapper userMapper;
    @RequestMapping("/select")
    public List<User> select()
    {
        List<User> userList = userMapper.getAllNoTenant();
        return userList;
    }
}

  1. postman 访问测试

在这里插入图片描述

  • 21
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值