很强!Mybatis plus 学习教程 “手写SQL配置” “Mapper多参数传参” + 坑点说明

Mybatis plus 使用

  1. 改pom : 不仅要加入依赖,注意还有build!!!!!!

    <dependencies>
    		<!--mybatis-plus-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
            </dependency>
    
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <scope>test</scope>
            </dependency>
            <!--mybatis-plus 代码生成器-->
            <dependency>
                <groupId>org.apache.velocity</groupId>
                <artifactId>velocity-engine-core</artifactId>
            </dependency>
    
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-generator</artifactId>
                <scope>test</scope>
            </dependency>
    </dependencies>
    <!-- 项目打包时会将java目录中的*.xml文件也进行打包 -->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    
  2. 写yml

    mybatis-plus:
      mapper-locations: classpath:com/zjazn/smallarea/mapper/xml/*.xml
    
  3. 主启动类,类上追加注解

    @MapperScan("com.zjazn.smallarea.mapper")
    
  4. 结构生成器,即entity、mapper、service 、controller

    可以直接运行,需要修改数据库连接信息与要生成结构对应的表(查看注释进行修改)

    import com.baomidou.mybatisplus.annotation.DbType;
    import com.baomidou.mybatisplus.annotation.IdType;
    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.DateType;
    import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    import org.junit.Test;
    
    /**
     * @author
     * @since 2018/12/13
     */
    public class CodeGenerator {
    
        @Test
        public void run() {
    
            // 1、创建代码生成器
            AutoGenerator mpg = new AutoGenerator();
    
            // 2、全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            //代码生成的绝对路径!!
            gc.setOutputDir("/home/nor/code/i/SmallArea/distributed-smallarea-service/product-service/src/main/java/");
    
            gc.setAuthor("testjava");
            gc.setOpen(false); //生成后是否打开资源管理器
            gc.setFileOverride(false); //重新生成时文件是否覆盖
    
            //UserServie
            gc.setServiceName("%sService");    //去掉Service接口的首字母I
    
            gc.setIdType(IdType.ID_WORKER_STR); //主键策略
            gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
            gc.setSwagger2(true);//开启Swagger2模式
    
            mpg.setGlobalConfig(gc);
    
            // 3、数据源配置 !!
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://localhost:3306/area_product?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
            dsc.setDriverName("com.mysql.jdbc.Driver");
            dsc.setUsername("root");
            dsc.setPassword("3333");
            dsc.setDbType(DbType.MYSQL);
            mpg.setDataSource(dsc);
    
            // 4、包配置!!!
            PackageConfig pc = new PackageConfig();
            //包  com.atguigu.eduservice
            pc.setParent("com.zjazn");
            pc.setModuleName("smallarea"); //模块名
    
            //包  com.atguigu.eduservice.controller
            pc.setController("controller");
            pc.setEntity("entity");
            pc.setService("service");
            pc.setMapper("mapper");
            mpg.setPackageInfo(pc);
    
            // 5、策略配置
            StrategyConfig strategy = new StrategyConfig();
    
            //哪些表要生成!!
            strategy.setInclude("goods","goods_detail","goods_type_global","goods_type_local");
    
            strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
            strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
    
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
            strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
    
            strategy.setRestControllerStyle(true); //restful api风格控制器
            strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
    
            mpg.setStrategy(strategy);
    
    
            // 6、执行
            mpg.execute();
        }
    }
    
  5. 使用mybatis plus强大功能, 基本使用就是注入service层来使用CURD方法,还可以注入Mapper使用CURD方法。

    https://baomidou.com/guide/crud-interface.html

    条件查询:

    
    
    LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
    //设置等值条件
    userWrapper.eq(User::getUsername,username);
    //模糊查询
    userWrapper.like(User::getUsername,userFo.getUsername());
    //追加条件查询
    userWrapper.apply("DATE(birth) <= STR_TO_DATE('1999-07-21 23:59:59','%Y-%m-%d %H:%i:%s')");
    User user = userService.getOne(userWrapper);
    

    条件带分页

      QueryWrapper<Star> starQueryWrapper = new QueryWrapper<>();
      starQueryWrapper.select(" goods_id , AVG(star) ");
      starQueryWrapper.in("goods_id",goods_ids);
      starQueryWrapper.groupBy("goods_id");
      Page<Star> page = new Page<>(page_number, item_number);
      IPage<Star> iPage = starMapper.selectPage(page, starQueryWrapper);
      List<Star> records = iPage.getRecords();
    

  6. (手写)多条件查询,mapper接口:

    package com.zjazn.smallarea.mapper;
    
    import com.zjazn.smallarea.entity.Goods;
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.zjazn.smallarea.entity.goods;
    import org.apache.ibatis.annotations.Param;
    
    import java.util.List;
    
    /**
     * <p>
     *  Mapper 接口
     * </p>
     *
     * @author testjava
     * @since 2021-06-22
     */
    
    
    public interface GoodsMapper extends BaseMapper<Goods> {
        List<goods> getGoodsByGlobalTypeId(@Param("id") String id,@Param("start_number") Integer start_number , @Param("item_number") Integer item_number );
    
    }
    
    
  7. XML

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.zjazn.smallarea.mapper.GoodsMapper">
    
    
        <resultMap id="goodsLimit" type="com.zjazn.smallarea.entity.goods">
            <id column="id" property="id" jdbcType="VARCHAR"></id>
            <result column="store_id" property="store_id" jdbcType="VARCHAR"></result>
            <result column="name" property="name" jdbcType="VARCHAR"></result>
            <result column="describe" property="describe" jdbcType="VARCHAR"></result>
            <result column="price" property="price" jdbcType="DECIMAL"></result>
            <result column="cover" property="cover" jdbcType="VARCHAR"></result>
        </resultMap>
        
        <select id="getGoodsByGlobalTypeId" resultType="com.zjazn.smallarea.entity.goods" >
            SELECT g.id, g.store_id ,gd.name,gd.describe, gd.price, gd.cover FROM goods g
            LEFT JOIN goods_detail  gd    ON g.id = gd.goods_id
            WHERE g.partition_global_id=#{id} LIMIT #{start_number},#{item_number};
        </select>
    
    
    </mapper>
    
    

    注意,XML取值还可以使用 #{0} #{1} ... 。
    坑点:如果取出的是字符串,不要再加''了!!比如id是String类型,应是id=#{id} 而不是id='#{id}'
    注意点:在进行模糊查询时,我们不能这样写'%#{search}%’ 这样是不对的,最好是concat('%', #{search},'%') 或次选 ’%${search}%‘ ,参考自:点击跳转
    注意点:插入操作中,传的是对象,这时我们不要使用@Param 这是传多个参数时使用的,还有使用后,我们取值就不能 #{对象参数名} 来取值会报错。

posted @ 2021-06-27 12:25  小庄的blog  阅读(1238)  评论(0编辑  收藏  举报