MyBatis-Plus 多表分页动态拼接SQL

本文介绍Mybatis-Plus多表分页查询及动态SQL相关内容,涵盖pom.xml配置、配置文件设置、Service、Mapper和XML编写。还特别提到动态SQL中字符串参数情况,当只有一个参数时可用_parameter代表,使用@Param则用指定参数值代替。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考文章:https://www.jianshu.com/p/759b6430ed5b
一、pom.xml

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.7.1</version>
</dependency>
<dependency>
 <build>
        <resources>
            <!--引入静态文件-->
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
            <!--引入mapper对应的xml文件-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

二、配置文件

yml:

mybatis-plus:
  type-aliases-package: com.harmonycloud.sfc.web.patrol.model.entity
  #扫描xml文件
  mapper-locations: classpath*:com/harmonycloud/sfc/web/patrol/mapper/xml/*.xml
  global-config:
    db-config:
      logic-not-delete-value: 1
      logic-delete-value: 0


配置类:

@Configuration
@MapperScan("com.harmonycloud.sfc.web.patrol.mapper")
public class MybatisPlusConfig {

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

    /**
     * 逻辑删除
     */
    @Bean
    public ISqlInjector iSqlInjector(){
        return new LogicSqlInjector();

    }
    /**
     * 打印 sql
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        //格式化sql语句
        Properties properties = new Properties();
        properties.setProperty("format", "true");
        performanceInterceptor.setProperties(properties);
        return performanceInterceptor;
    }
}

三、Service

    @Override
    public Page<Constant> getConstantByDtoAndPage(ConstantDto dto) {
        
        #构建分页查询对象
        Page<Constant> queryPage = new Page<>(dto.getPageNum(),dto.getPageSize());
        
        #构建查询条件
        QueryWrapper wrapper = new QueryWrapper(dto);

        #调用Mapper自定义接口
      List<Constant> list = baseMapper.getConstantByContentAndCategory(queryPage,wrapper);

      queryPage.setRecords(list);
        
        return queryPage;
    }

四、Mapper

public interface ConstantMapper extends BaseMapper<Constant> {

    #此处Page<Constant> 也可不指定泛型,直接为Page
    List<Constant> getConstantByContentAndCategory(Page<Constant> page, @Param("qw") QueryWrapper wrapper);
}

五、XML

  <select id="getConstantByContentAndCategory"         parameterType="com.harmonycloud.sfc.web.patrol.model.dto.ConstantDto"
            resultType="com.harmonycloud.sfc.web.patrol.model.entity.Constant">
        SELECT
          a.ConstID,
          a.Content,
          a.CategoryID,
          b.Name as Category
        FROM
          (SELECT
            t.ConstID,
            t.Content,
            t.CategoryID
          FROM
            siconstant t
          WHERE t.Active = 1
          <if test="qw.entity.Content!=null and qw.entity.Content!=''">
            and t.Content LIKE CONCAT('%',#{qw.entity.Content,jdbcType=VARCHAR},'%')
          </if>
          ) a
          LEFT JOIN siconstantcategory b
            ON a.CategoryID = b.CategoryId
        <if test="qw.entity.Categroy!=null and qw.entity.Categroy!=''">
        WHERE Name LIKE CONCAT('%',#{qw.entity.Categroy,jdbcType=VARCHAR},'%')
        </if>
    </select>

注意:动态SQL中字符串参数时:
当只有一个参数的时候,可以使用_parameter,它就代表了这个参数,如果使用@Param的话,会使用指定的参数值代替

<think>好的,我现在需要解决用户的问题:使用MyBatis-Plus实现分页查询,并且基于子条件进行动态搜索。用户之前提到的引用中提到了需要自定义Vo对象和SQL语句,以及使用Page对象设置分页参数。我需要结合这些信息,给出一个清晰的实现步骤。首先,用户的需求是分页,并且子条件作为搜索条件。这意味着在SQL中需要联查询,并且根据子的某些字段进行过滤。MyBatis-Plus本身不支持联查,所以需要手动编写SQL,这一点引用1和引用2都提到了。同时,分页需要配置分页插件,如引用4中的配置类,添加分页拦截器。接下来,我需要考虑如何动态添加子条件。动态SQL可以通过MyBatis的XML文件中的<if>标签实现,根据传入的参数是否存在来拼接条件。例如,如果子有一个name字段需要作为搜索条件,可以在WHERE子句中使用<if test="bo.subName !=null">来动态添加。然后,关于分页的实现,用户需要创建Page对象,设置current和size参数,然后调用Mapper的自定义方法,返回分页结果。引用3中的UserMapper示例展示了如何定义接口方法,参数中使用IPage和查询条件对象,这可以作为参考。还需要注意,查询结果需要封装到Vo对象中,因为查询的字段可能涉及,Vo对象可以包含这些字段。例如,用户查询用户和角色信息,Vo可能包含用户ID、用户名、角色名等字段。 可能还需要配置MyBatis-Plus分页插件,确保分页功能正常。如引用4中的配置类,添加分页拦截器并指定数据库类型。现在需要检查步骤是否正确:配置分页插件、创建Vo对象、编写联查询的SQL(包含动态条件)、定义Mapper接口方法、调用分页方法。这应该能覆盖用户的需求。可能的疑问点:动态条件的处理是否正确,分页参数是否正确传递,联查询的SQL语法是否正确。需要确保在XML映射文件中正确使用参数对象中的属性,并且在Java代码中正确传递Page对象和查询条件。 最后,生成相关问题,需要考虑用户可能的后续问题,比如动态条件更情况如何处理,性能优化,或者如何实现查询等。</think>### 分步实现MyBatis-Plus分页查询(子条件动态搜索) #### 一、配置分页插件 在MyBatis-Plus配置类中添加分页拦截器: ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` 此配置支持MySQL分页语法[^4]。 #### 二、创建VO对象 定义接收查询结果的VO类,包含主和子字段: ```java @Data public class UserRoleVO { private Long userId; private String userName; private String roleName; // 子字段 private LocalDateTime createTime; } ``` #### 三、Mapper接口定义 在Mapper接口中声明分页查询方法: ```java public interface UserMapper extends BaseMapper<User> { IPage<UserRoleVO> selectUserRolePage( @Param("page") IPage<UserRoleVO> page, @Param("bo") UserRoleQueryBO queryBo ); } ``` 其中`UserRoleQueryBO`为包含子条件的查询参数对象[^3]。 #### 四、XML映射文件实现 ```xml <select id="selectUserRolePage" resultType="UserRoleVO"> SELECT u.id as userId, u.name as userName, r.role_name as roleName FROM user u LEFT JOIN role r ON u.role_id = r.id <where> <!-- 动态条件 --> <if test="bo.roleName != null and bo.roleName != ''"> AND r.role_name LIKE CONCAT('%', #{bo.roleName}, '%') </if> <if test="bo.minCreateTime != null"> AND r.create_time >= #{bo.minCreateTime} </if> </where> </select> ``` 通过`<where>`和`<if>`标签实现动态条件拼接[^2]。 #### 五、Service层调用 ```java public IPage<UserRoleVO> getUserRolePage(int current, int size, UserRoleQueryBO queryBo) { Page<UserRoleVO> page = new Page<>(current, size); return userMapper.selectUserRolePage(page, queryBo); } ``` 分页参数通过Page对象传递,查询结果自动包含分页信息[^1]。 #### 六、动态条件扩展 若要支持更动态条件,可在查询参数对象中添加字段并在XML中扩展: ```java @Data public class UserRoleQueryBO { private String roleName; // 子条件 private LocalDateTime minCreateTime; private Integer status; // 可扩展新条件 } ``` XML中添加对应判断条件: ```xml <if test="bo.status != null"> AND r.status = #{bo.status} </if> ``` ### 注意事项 1. **联字段映射**:确保SQL别名与VO字段名称一致 2. **索引优化**:涉及子条件的字段建议添加索引 3. **N+1问题**:避免在循环中查询关联数据 4. **参数校验**:在Service层对查询参数进行有效性验证 ### 示例调用 ```java UserRoleQueryBO queryBo = new UserRoleQueryBO(); queryBo.setRoleName("admin"); queryBo.setMinCreateTime(LocalDateTime.now().minusDays(7)); IPage<UserRoleVO> pageResult = userService.getUserRolePage(1, 10, queryBo); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值