【springboot】 Mybatis-plus使用及注意事项

2 篇文章 0 订阅
2 篇文章 0 订阅

Mybatis-plus 使用及注意事项

Mybatis-plus官网(不定时无无)

1. pml依赖

        <!--		mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.4</version>
        </dependency>
        <!--		mybatis plus自动代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--模板引擎freemarker或默认的Velocity引擎模板-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version>
        </dependency>
        <!--		mybatis-plus-join联表查询-->
        <dependency>
            <groupId>com.github.yulichang</groupId>
            <artifactId>mybatis-plus-join</artifactId>
            <version>1.2.4</version>
        </dependency>

模板引擎freemarker可更换为默认的Velocity引擎模板

  <dependency>
          <groupId>org.apache.velocity</groupId>
           <artifactId>velocity-engine-core</artifactId>
           <version>2.3</version>
       </dependency>

2.配置文件(yaml为例)

#数据库配置等
#...
#关闭thymeleaf模板引擎
spring:
	thymeleaf:
    	cache: false
#mybatis-plus配置
mybatis-plus:
	type-aliases-package: com/euphoria/shop/entity
	mapper-locations: classpath:com/euphoria/shop/mapper/xml/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
     #逻辑删除配置
      logic-delete-value: 1      
      logic-not-delete-value: 0
  • 若mapper位置位于resource下,mapper-locations可使用默认值
    mapper-locations: classpath*:/mapper/**/*.xml

3.MybatisPlusConfig 配置类

@MapperScan("com.euphoria.mapper")
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
    //分页
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    //乐观锁
    @Bean
    public MybatisPlusInterceptor OptimisticLockerInnerInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }
}

4.实体类中注解开发

 @TableField(fill = FieldFill.INSERT)
    private LocalDateTime createTime;
 @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
  @TableLogic
    private Integer deleted;

5.使用mybatis-plus-join联表查询

依赖

    <dependency>
        <groupId>com.github.yulichang</groupId>
        <artifactId>mybatis-plus-join</artifactId>
        <version>1.2.4</version>
    </dependency>

使用前需将mapper接口继承的baseMapper改为MPJBaseMapper

public interface UserCartMapper extends MPJBaseMapper<UserCart>。。。

使用案例

    IPage<UserCartVo> goodsPage = baseMapper.selectJoinPage(new Page<>(currentPage, pageSize), UserCartVo.class,
                new MPJLambdaWrapper<UserCartVo>().selectAll(UserCart.class)
                        .select(Goods::getName, Goods::getPicture, Goods::getPriceNew, Goods::getPriceOld, Goods::getStore)
                        .leftJoin(Goods.class, Goods::getGoodsId, UserCart::getGoodsId)
                        .eq(UserCart::getUserId, userCart)
                        .orderByDesc(UserCart::getUserCartId)
        );

复杂联表建议还是自写xml⑧hhhhhh.

6. mybatis plus自动代码生成器(数据自改)

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

在测试类中运行:

 public static void main(String[] args) {
        String propath = System.getProperty("user.dir");
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/shop?characterEncoding=utf-8&serverTimezone=Asia/Shanghai",
                        "root", "123456")//数据库配置
                .globalConfig(builder -> {
                    builder.disableOpenDir()//不自动打开文件位置
                            .author("euphoria")
                            .enableSwagger()               // 开启 swagger 模式
                            .outputDir(propath + "/src/main/java");// 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.euphoria") // 设置父包名
                            .moduleName("shop") // 设置父包模块名  组合即com.euphoria.shop...
                            .entity("entity")
                            .service("Service")
                            .serviceImpl("Service.impl")
                            .mapper("mapper")
                            .controller("controller");
                })
                .strategyConfig(builder -> {
                    builder.addInclude("user")// 设置需要生成的表名,对应数据库表名
                            //entity配置
                            .entityBuilder()
                            .enableLombok()
                            //以下视情况而定
                            //版本
                            .versionColumnName("version")
                            .versionPropertyName("version")
                            //逻辑删除
                            .logicDeleteColumnName("deleted")
                            .logicDeletePropertyName("deleted")
                            //创建更新时间
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE))
                            //ID类型
                            .idType(IdType.ASSIGN_UUID)

                            //controller
                            .controllerBuilder()
                            .enableRestStyle()
                            //service
                            .serviceBuilder()
                            .formatServiceFileName("%sService")  //去掉开头I
                            .formatServiceImplFileName("%sServiceImp")               
                    ;
                })
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

7.注意事项(BUG日记)

  • 启动类上mapperscan 扫描需写对,即@MapperScan("com.euphoria.shop.mapper")

否则报错UnsatisfiedDependencyException: Error creating bean with name ‘userServiceImp’

Caused by: org.springframework.beans.factory.BeanCreationException:
      Error creating bean with name 'sqlSessionFactory' defined in class path resource
[com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]
      Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: 
Failed to instantiate[org.apache.ibatis.session.SqlSessionFactory]: Factory method'sqlSessionFactory' threw
exception; nested exception is org.apache.ibatis.type.TypeException: The alias
'Collection' is already mapped to the value 'java.util.Collection'.

解决:修改类名,避免重复

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值