使用MybatisPlus中遇到的问题

1、简单的查询

QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
queryWrapper.like(!StringUtils.isEmpty(name),Employee::getName,name);

Employee::getName 会报  String is not a functional interface 的错误

为了解决这个问题可以有两种方法

//第一种方法 ,可以使用lambda表达式的方式声明对象

LambdaQueryWrapper<Employee> query = new LambdaQueryWrapper<>();

//第二种方法, 在queryWrapper后添加 lambda
QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().like(!StringUtils.isEmpty(name),Employee::getName,name);

2、分页

1、添加拦截器
@Configuration
public class MybatisPlusConfig{

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}

3、mybatis-plus 的逆向生成实体类

3.1依赖

<!--数据库连接-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--逆向生成-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--模板-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

3.2输入要生成的表名

public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入要生成的表名:");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 构建代码生自动成器对象
        AutoGenerator mpg = new AutoGenerator();

        //构建全局配置对象
        GlobalConfig gc = new GlobalConfig()
                .setOutputDir(System.getProperty("user.dir") + "/src/main/java") // 输出文件路径
                .setAuthor("内卷") // 设置作者
                .setOpen(false) // 是否打开资源管理器
                .setFileOverride(true)// 是否覆盖原来生成的
                .setIdType(IdType.NONE)// 主键策略
                .setBaseResultMap(true)// 生成resultMap
                .setBaseColumnList(true)// XML中生成基础列
                .setServiceName("%sService");// 生成的service接口名字首字母是否为I,这样设置就没有I
        ;

        DataSourceConfig dsc = new DataSourceConfig()
                .setUrl("jdbc:mysql://localhost:3537/reggie?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true")
                .setDriverName("com.mysql.cj.jdbc.Driver")
                .setUsername("root")
                .setPassword("root")
                .setDbType(DbType.MYSQL);

        PackageConfig pc = new PackageConfig()
                .setParent("com.baomidou")
                .setEntity("entity")
                .setService("service")
                .setMapper("mapper")
                .setModuleName("generator");

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        List<FileOutConfig> focList = new ArrayList<>();
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(com.baomidou.mybatisplus.generator.config.po.TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return System.getProperty("user.dir") + "/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);

        TemplateConfig templateConfig = new TemplateConfig();
        /*templateConfig.setEntity("templates/entity2.java");
                .setService("")
                .setController("");*/

        templateConfig.setXml(null);

        StrategyConfig strategyConfig = new StrategyConfig()
                .setCapitalMode(true)// 开启全局大写命名
                .setNaming(NamingStrategy.underline_to_camel) // 下划线到驼峰的命名方式
                .setColumnNaming(NamingStrategy.underline_to_camel) // 下划线到驼峰的命名方式
                .setEntityLombokModel(true) // 是否使用lombok
                .setRestControllerStyle(true) // 是否开启rest风格
                .setSuperEntityColumns("id")
                .setInclude(scanner("").split(","))
                //设置要生成的表 用英文逗号分开
                .setControllerMappingHyphenStyle(true)
                .setTablePrefix(pc.getModuleName() + "_");
//                .setSuperControllerClass("你自己的父类控制器,没有就不用设置!")
//                .setSuperEntityClass(“你自己的父类实体,没有就不用设置!”)

        mpg.setGlobalConfig(gc);
        mpg.setDataSource(dsc);
        mpg.setPackageInfo(pc);
        mpg.setCfg(cfg);
        mpg.setTemplate(templateConfig);
        mpg.setStrategy(strategyConfig);
//        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();

    }

4、自动补全公共字段

@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;

@TableField(fill = FieldFill.INSERT)
private Long createUser;

@TableField(fill = FieldFill.INSERT_UPDATE)
private Long updateUser;

添加mybatisPlus的拦截器

@Configuration
public class MybatisPlusConfig{

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}

给公共字段赋值

@Configuration
public class MyMetaDataObjectConfig implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", GlobalSessionManager.getUserId());
        metaObject.setValue("updateUser",GlobalSessionManager.getUserId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser",GlobalSessionManager.getUserId());
    }
}

5、MybatisPlus 连接SQLServer 数据库

需要的依赖为

<!--Sqlserver-->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>sqljdbc4</artifactId>
			<version>4.0</version>
		</dependency>
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>6.2.0.jre8</version>
			<scope>runtime</scope>
		</dependency>
datasource:
    # 这是sqlserver的驱动
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    #sqlserver Url
    url: yoururl
    username: your username
    password: your password

Java的类型应与数据库类型保持一致,否则会报以下错误

Method com/microsoft/sqlserver/jdbc/SQLServerResultSet.getObject(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object; is abstract] with root cause

本文章会持续更新

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工作这么多年,学会了内卷

共同加油,继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值