基于MybatisPlus实现多表的关联查询,实现分页,多条件查询

1、缘由

实现商品表,通过表内的id关联查询到供应商表的name属性
商品表
如下所示
在这里插入图片描述
供应商表
如下所示
在这里插入图片描述

新建查询测试sql

注意,
1、查询tb_goods表的全部,所以用t1.*,查询t2表的name,并用supplierName替换名称
2、使用LEFT JOIN链入tb_supplier表,tb_goods为主表
3、使用on来判断连接条件
4、where下面是查询条件,用like模糊查询,个条件间使用 And连接而不是Add

SELECT
	t1.*, t2. NAME supplierName
FROM
	tb_goods t1
LEFT JOIN tb_supplier t2 
ON t1.supplier_id = t2.id
WHERE
t1.name like '%S%'
AND t1.code like '%Spring%'
AND t1.supplier_id=1

建立dao层接口,实体类,以及接受请求参数类

请求参数类
建立请求参数类,用于接收前端模糊查询的结果
前端查询:商品名称,商品编码,商品供应商名称

package com.jhj.member.req;

import lombok.Data;

/**
 * @program: jhjmember
 * @ClassName GoodsREQ
 * @description:
 * @author:蒋皓洁
 * @create: 2020-08-19 15:21
 * @Version 1.0
 * 商品的请求类,接收请求参数
 **/
@Data
public class GoodsREQ {
    /**
     * 商品名称
     */
    private String name;

    /**
     * 商品编码
     */
    private String code;
    /**
     * 供应商id
     */
    private Integer supplierId;
}

entity实体类
实体类是代码生成器自动生成的,字段映射的是数据库tb_goods表的字段
但是注意的是,因为没有tb_supplier表供应商名字的字段,但是又要添加,所以采用 @TableField(exist = false)标识,不然启动时候在tb_goods中找不到supplierName就会报错

 /**
     * goods表中没有这个字段,所以这里要用,TableFiled标识字段,不然要报错
     */
    @TableField(exist = false)
    private  String supplierName;

package com.jhj.member.entity;

import java.math.BigDecimal;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 商品信息表
 * </p>
 *
 * @author 蒋皓洁
 * @since 2020-08-18
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_goods")
public class Goods implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    /**
     * 商品名称
     */
    private String name;

    /**
     * 商品编码
     */
    private String code;

    /**
     * 商品规格
     */
    private String spec;

    /**
     * 零售价
     */
    private BigDecimal retailPrice;

    /**
     * 进货价
     */
    private BigDecimal purchasePrice;

    /**
     * 库存数量
     */
    private Integer storageNum;

    /**
     * 供应商id
     */
    private Integer supplierId;


    /**
     * goods表中没有这个字段,所以这里要用,TableFiled标识字段,不然要报错
     */
    @TableField(exist = false)
    private  String supplierName;


}

mapper层接口
1、第一个参数传递分页的对象page (此对象封装当前页码,还有显示查询多少)
2、第二个参数,查询条件,@Param取别名, @Param(“req”)这个取的别名,方便xml里面使用

public interface GoodsMapper extends BaseMapper<Goods> {
    /**
     *
     * @param page
     * @param req
     * @return
     *
     *
     * 分页查询商品的列表
     * 1、第一个参数传递分页的对象page (此对象封装当前页码,还有显示查询多少)
     *
     * 2、第二个参数,查询条件,@Param取别名,
     *  @Param("req")这个取的别名,方便xml里面使用
     */

      IPage<Goods>searchPage(IPage<Goods> page, @Param("req")GoodsREQ req);
}

xml中写入sql
拼接如下所示,但是,注意的是

1、 < select id=“searchPage” resultType=“Goods”>
searchPage表mapper中的方法名称,Goods表示实体类的名称
在application.yml中配置了实体类的包,所以不用加全路径

mybatis-plus:
  # 扫描实体类所在的包,这样在mapper.xml文件中就不用配置实体类全路径,直接写类名就行
  type-aliases-package: com.jhj.member.entity
  #  扫描xml包下面的xml文件
  mapper-locations: classpath:com/jhj/member/mapper/xml/**.xml
  #  配置日志级别

在这里插入图片描述

2、where下面的拼接
WHERE 1=1
判断传入的值是否为空 req.name,这就用到了别名@Param(“req”),映射GoodsREQ req,
t1.name的name是数据库的字段,两个之间用and连接,不是add
每个查询条件之间也是用and连接

  < if test="req.name !=null and req.name!=''">
            and t1.name like CONCAT('%',#{req.name},'%')
  </ if >
<?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.jhj.member.mapper.GoodsMapper">

    <select id="searchPage" resultType="Goods">
        SELECT
        t1.*, t2.name supplierName
        FROM
        tb_goods t1
        LEFT JOIN tb_supplier t2 ON t1.supplier_id = t2.id
        WHERE 1=1
        <if test="req.name !=null and req.name!=''">
            and t1.name like CONCAT('%',#{req.name},'%')
        </if>
        <if test="req.code!=null and req.code!=''">
            and  t1.code like CONCAT('%',#{req.code},'%')
        </if>
        <if test="req.supplierId!=null">
            and t1.supplier_id=#{req.supplierId}
        </if>
    </select>
</mapper>

service层的编写

接口还是传入,页数page,每页显示多少size,和查询条件参数封装的req

public interface IGoodsService extends IService<Goods> {
    List<Goods>SlectBySupplierId(int id);

    Result search (Long page, Long size, GoodsREQ req);
}

serviceImpl
因为mapper.xml已经对查询条件进行筛选和拼接了,所以这里不做条件的拼接,
传入分页对象和查询条件进行查询。

  @Override
    public Result search(Long page, Long size, GoodsREQ req) {
        /**
         *因为mapper.xml已经对查询条件进行筛选和拼接了
         */
        if (req==null){
            req=new GoodsREQ();
        }
        IPage data = baseMapper.searchPage(new Page<Goods>(page, size), req);
        return Result.ok(data);
    }

control层

@RequestBody (required = false) 表示可以不传查询条件

  @Autowired
    private IGoodsService goodsService;


    /**
     *
     * @param page
     * @param size
     * @param req
     * @return
     *
     */
    @PostMapping("/list/search/{page}/{size}")
    public Result search(
            @PathVariable("page") long page,
            @PathVariable("size") long size,
            @RequestBody (required = false)    GoodsREQ req
            ){

       return goodsService.search(page,size,req);
    }
  • 20
    点赞
  • 113
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
MyBatis-Plus是一个基于MyBatis的增强工具,它提供了很多便捷的功能来简化开发。在MyBatis-Plus中,多表关联查询分页查询都是支持的。 对于多表关联查询MyBatis-Plus提供了多种方式来实现,其中一种常用的方式是使用@TableName注解和@JoinTable注解。首先,在实体类上使用@TableName注解指定表名,然后在需要关联的字段上使用@JoinTable注解指定关联条件。通过这种方式,可以方便地进行多表关联查询。 下面是一个示例代码,演示了如何使用MyBatis-Plus进行多表关联查询: ```java // 实体类1 @TableName("table1") public class Entity1 { @TableId private Long id; private String name; // ... } // 实体类2 @TableName("table2") public class Entity2 { @TableId private Long id; private Long entityId1; private String info; // ... } // Mapper接口 public interface EntityMapper extends BaseMapper<Entity1> { @Select("SELECT t1.*, t2.info FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.entity_id1") List<Entity1> selectEntityWithInfo(); } ``` 在上述示例中,Entity1和Entity2分别对应数据库中的table1和table2表。通过@JoinTable注解,我们可以在EntityMapper接口中定义一个自定义的查询方法selectEntityWithInfo(),该方法使用了LEFT JOIN实现多表关联查询,并返回Entity1的列表。 对于分页查询,MyBatis-Plus提供了Page对象来支持分页功能。在查询方法中,可以通过传入Page对象来指定分页参数,然后使用MyBatis-Plus提供的分页查询方法进行查询。查询结果会被封装到Page对象中,包含了总记录数、当前页数据等信息。 下面是一个示例代码,演示了如何使用MyBatis-Plus进行分页查询: ```java // Mapper接口 public interface EntityMapper extends BaseMapper<Entity1> { @Select("SELECT * FROM table1") IPage<Entity1> selectEntityWithPage(Page<Entity1> page); } ``` 在上述示例中,EntityMapper接口中的selectEntityWithPage()方法使用了Page对象作为参数,并通过@Select注解指定了查询语句。在实际调用时,可以创建一个Page对象并传入分页参数,然后调用selectEntityWithPage()方法进行分页查询。 以上就是使用MyBatis-Plus进行多表关联查询分页查询的简单介绍。如果你还有其他问题,请继续提问。
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值