MyBatisPlus使用中几个需要注意的点

本文介绍了在使用MyBatisPlus时需要注意的关键点,包括在pom文件中添加依赖,插入操作时主键ID的处理(AUTO和INPUT两种模式),开启SQL日志的配置,代码生成器的使用及解决mapper.xml加载问题,以及分页查询的配置和自定义SQL的运用。
摘要由CSDN通过智能技术生成

一、需要在pom中添加的坐标和解释

	<!-- MyBatisPlus包 -->
	<dependency>
	      <groupId>com.baomidou</groupId>
	      <artifactId>mybatis-plus-boot-starter</artifactId>
	      <version>3.3.1</version>
	</dependency>

	<!--代码生成器,自动生成bean,service,controller,mapper-->
	<dependency>
		    <groupId>com.baomidou</groupId>
		    <artifactId>mybatis-plus-generator</artifactId>
		    <version>3.3.1</version>
	</dependency>

	<!--代码生成器-默认模板引擎-->
	<dependency>
		    <groupId>org.apache.velocity</groupId>
		    <artifactId>velocity-engine-core</artifactId>
		    <version>2.2</version>
	</dependency>
	<!--代码生成器-可选模板引擎-->
	<dependency>
		    <groupId>org.freemarker</groupId>
		    <artifactId>freemarker</artifactId>
		    <version>2.3.30</version>
	</dependency>

二、插入时主键id的问题

对象的主键字段需要添加如下设置

@TableId(value = "id", type = IdType.AUTO)
private Integer id;

其中IdType的可选值为

public enum IdType {
    AUTO(0),//主键自增
    NONE(1),//不为主键
    INPUT(2),//手动输入主键
    ASSIGN_ID(3),//分配ID,主键类型为Number(Long和Integer)或String
    ASSIGN_UUID(4)//分配UUID,主键类型为String
    }

AUTO

id设置成自增的时候,insert的时候就id就会被忽略,即使设置了值也无效;
返回的值可以通过getId获取插入数据的主键id值

	userMapper.insert(user);
	Integer id = user.getId();

INPUT

如果想要手动设置插入的id,主键类型可是设置为input,设置之后在insert的时候就必须手动
设置id值,不然就会insert失败。返回值中自然也就已经有了插入的数据id。

三、设置显示sql日志

在.yml文件中设置

#mybatisplus配置
mybatis-plus: 
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #开启日志打印

四、代码生成器

需要的坐标已在中已经说明

创建CodeGenerator代码生成类

package com.hao.springcloud.cloudproviderpayment8001.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Scanner;

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置 D:\springcloud2020\cloud-provider-payment8001\src\main\java\com\hao\springcloud\cloudproviderpayment8001
        GlobalConfig gc = new GlobalConfig();
        String projectPath = "D://springcloud2020/cloud-provider-payment8001";
        gc.setOutputDir(projectPath+"/src/main/java");
        gc.setAuthor("liguanghao");//作者
        gc.setOpen(false);//是否打开输出目录
        gc.setFileOverride(true);//每次生成覆盖之间的
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setServiceName("%sService");//service前面没有"I"
        gc.setBaseResultMap(true);//生成基本的sql语句在xml中
        gc.setBaseColumnList(true);//生成sql片段在xml中
        gc.setIdType(IdType.AUTO);//指定id策略,auto:主键自增
        gc.setDateType(DateType.ONLY_DATE);//指定时间类型
        mpg.setGlobalConfig(gc);

        //包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));//可以手动数据模块名
        pc.setParent("com.hao.springcloud.cloudproviderpayment8001");
        pc.setEntity("bean");
		pc.setController("controller");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setMapper("mapper");
        pc.setXml("mapper.xml");
        mpg.setPackageInfo(pc);

		// 配置模板:可以配置是否生成entity、service、mapper、controller类
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setService(null);//设置不生成service类
        templateConfig.setServiceImpl(null);//设置不生成serviceImpl类
        mpg.setTemplate(templateConfig);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setUrl("jdbc:mysql://localhost:3306/springcloud2020?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        /*数据库表配置*/
        StrategyConfig strategy = new StrategyConfig();
        strategy.setCapitalMode(true);//全局大写命名
        strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);//生成 @RestController 控制器
        
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        //strategy.setInclude("area");//或者可以写死需要生成代码的表,每次修改
        
        strategy.setControllerMappingHyphenStyle(true);//驼峰转连字符
        //strategy.setTablePrefix(pc.getModuleName() + "_");//表前缀
        mpg.setStrategy(strategy);
        
        mpg.execute();
    }
}

具体可查看官网文档

查看目录生成文件目录结构

在这里插入图片描述

加载不到mapper.xml的问题-加两处配置

由于自动生成的mapper.xml文件在java的目录下,而未在resources下,所以需要在多两处配置

1. pom添加

		<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
            </resource>
            <!--为了resources下的配置文件生效,必须把下边的也配上去-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.yml</include>
                </includes>
            </resource>
        </resources>

2.yml文件添加

#mybatisplus配置
mybatis-plus: 
  mapper-locations: classpath:com/hao/springcloud/cloudproviderpayment8001/mapper/xml/*.xml
  #或者直接写:
  mapper-locations: classpath:**/mapper/xml/*.xml

在这里插入图片描述

五、关于分页

查询中用到分页,例如

    @GetMapping("getUserList")
    public R getUserList(String roles,int current,int size){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper.like("roles",roles);

        queryWrapper.orderByDesc("id");//根据id倒叙排序

        Page Page = new Page(current,size);//分页

        IPage data = userMapper.selectPage(Page, queryWrapper);

        return R.ok(data);

    }

分页是不起作用的,需要添加配置:

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

自定义sql分页查询:https://www.jianshu.com/p/245f37f69eb9

自定义sql使用MP的一些特性

  • controller:
@GetMapping("/getDoctorsByHospital")
    
    public R<IPage<UserDoctor>> getUserToken(int current,int size,String orgId,String name){
        log.info("分页查询集合:"+"orgId:"+orgId+"  name:"+name+"  current:"+current+"  size:"+size);
        QueryWrapper<UserDoctor> queryWrapper = new QueryWrapper<UserDoctor>();
        Map<String, Object> params = new HashMap<String, Object>();
        String hospitalByOrgId = hospitalUtils.getHospitalByOrgId(orgId);
        queryWrapper.isNull("h.id");
        params.put("u.hospital_guid", hospitalByOrgId);
        params.put("u.status", 0);
        queryWrapper.allEq(params);
        queryWrapper.like(StringUtils.isNotBlank(name),"u.name",name);
        queryWrapper.orderByDesc("u.id");
        IPage<UserDoctor> page = new Page<>(current,size);
        IPage<UserDoctor> userDoctorPage = userDoctorMapper.selectPageByMapping(page, queryWrapper);
        log.info("分页查询集合返回:"+userDoctorPage.getRecords());
        return R.ok(userDoctorPage);
    }
  • mapper:
    #注意:这里的page要放在第一个参数,否则会报错
    Page<UserDoctor> selectPageByMapping(IPage page, @Param(Constants.WRAPPER) Wrapper<UserDoctor> queryWrapper);
  • mapper.xml:
<select id="selectPageByMapping" resultType="com.bsh.ih.org.base.entity.UserDoctor" >
        SELECT u.*, b.mainId AS departmentIdts
        FROM `user_doctor` u
        LEFT JOIN idmapping_bt b ON u.department_id = b.guid
        LEFT JOIN idmapping_hbt h ON u.hospital_guid = h.hospitalGuid AND u.guid = h.guid AND h.enabled =1
        ${ew.customSqlSegment}
  </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值