MybatisPlus查询注解,使用注解即可实现复杂场景的查询需求、支持多表关联!

 Mybatis Plus 查询注解,复杂的查询业务需求通过QO + Query注解优雅的实现,提升开发效率(源码已开源,文章最后)。

1. 支持多表关联查询;

2. 支持 常用类型:EQ、LK(LIKE)、LLK(LEFT LIKE)、RLK(RIGHT LIKE)、GT、LT、GE、LE、IN、NIN(NOT IN)、ES(EXISTS)、NES(NOT EXISTS)、BT(BETWEEN)、NBT(NOT BETWEEN)、INL(IS NULL)、NNL(NOT NULL) 等等;

3. 支持AND、OR 嵌套;

4. 支持自定义排序;

5. 支持前端控制条件(new 快速开发,解放生产力);

6. 支持后端自定义查询(new);

一、支持注解实现复杂查询逻辑,使用示例:

1.1. 注解查询类 GoodsQO (关键代码)

import com.example.czy.annotation.Query;
import com.example.czy.annotation.QueryOR;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @Author czy
 * @Date 2023-07-09
 **/
@Data
public class GoodsQO {
    /**
     * 多表关联查询时可以使用别名 如:g.id
     * 默认查询类型为 equal
     * id =
     */
    @ApiModelProperty(value = "商品ID")
    @Query(field = "g.id")
    private Long id;

    /**
     * like可以指定为:left like、like、right like
     * name like '1%'
     */
    @ApiModelProperty(value = "商品名称")
    @Query(type = Query.Type.RIGHT_LIKE)
    private String name;

    /**
     * between 支持集合、数组、逗号分割
     * create_Time between '2021-07-09' and '2023-07-09'
     */
    @ApiModelProperty(value = "商品创建时间区间逗号分割")
    @Query(field = "g.createTime", type = Query.Type.BETWEEN)
    private String createTime;

    /**
     * 多字段模糊匹配,适合一键搜索场景
     * (name like '%1%' or description like '%1%')
     */
    @ApiModelProperty(value = "商品或描述")
    @Query(likes = "name,description")
    private String keyword;

    /**
     * 嵌套查询注解@QueryOR 相当于 and (store_id is not null or goods_id is not null)
     */
    @QueryOR
    private StoreQO storeQO;

    /**
     *  排序如:createTime desc,id
     *  (order by create_time desc,id asc)
     */
    @ApiModelProperty(value = "排序,逗号分割")
    private String sort;

}

1.2. OR条件类 StoreQO(拓展)

import com.example.czy.annotation.Query;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @Author czy
 * @Date 2023-07-09
 **/
@Data
public class StoreQO {
    @ApiModelProperty(value = "门店ID", hidden = true)
    @Query(type = Query.Type.NOT_NULL)
    private String storeId;

    @ApiModelProperty(value = "商品ID", hidden = true)
    @Query(type = Query.Type.NOT_NULL)
    private String goodsId;
}

1.3 . Service业务实现类

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.czy.entity.Goods;
import com.example.czy.mapper.GoodsMapper;
import com.example.czy.qo.GoodsQO;
import com.example.czy.qo.base.PageQO;
import com.example.czy.service.GoodsService;
import com.example.czy.util.PageUtil;
import com.example.czy.util.QueryUtils;
import com.example.czy.vo.GoodsVO;
import org.springframework.stereotype.Service;

/**
 * @Author czy
 * @Date 2023-07-09
 **/
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Override
    public IPage<GoodsVO> pageByQO(PageQO page, GoodsQO qo) {
        QueryWrapper queryWrapper = QueryUtils.buildQueryWrapper(qo);
        return baseMapper.selectByQO(PageUtil.getPage(page), queryWrapper);
    }
}

1.4. Mapper 实现类

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.czy.entity.Goods;
import com.example.czy.vo.GoodsVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

/**
 * 商品
 *
 * @author czy
 * @date 2022-02-25
 */
@Mapper
public interface GoodsMapper extends BaseMapper<Goods> {
    /**
     * 根据QO查询
     *
     * @param page
     * @param wrapper
     * @return
     */

    @Select("select g.*,gs.store_id from goods g join goods_store gs on g.id = gs.goods_id ${ew.customSqlSegment}")
    IPage<GoodsVO> selectByQO(Page page, @Param(Constants.WRAPPER) Wrapper wrapper);
}

1.5. 接口测试

1.6. 最终SQL

   SELECT g.*, gs.store_id
    FROM goods g JOIN goods_store gs ON g.id = gs.goods_id
    WHERE  
    (
        name LIKE '1%'  
        AND g.create_time BETWEEN '2021-07-011' AND '2023-07-11'  
        AND ( name LIKE '%1%' OR description LIKE '%1%' )
        AND ( store_id IS NOT NULL OR goods_id IS NOT NULL)
    )
    ORDER BY create_time DESC, id ASC
    LIMIT 10

二. 支持前端控制查询条件,使用示例:

public Page<GoodsVO> pageByJson(PageQO page, String json) {
    // 前端传过来的json条件
    // String json = "[{\"name\":\"lk 张三\"},{\"id\":\"in 1,3,4,5\"}]";

    // 设置别名,all表示默认别名,即前端传过来所有字段默认别名为g
    Map<String, String> alialsMap = new HashMap();
    alialsMap.put("all", "g");

    QueryWrapper queryWrapper = QueryUtils.buildQueryWrapperJson(json, alialsMap);
    return baseMapper.selectByQO(PageUtil.getPage(page), queryWrapper);
}

// 翻译SQL
// SELECT * FROM goods WHERE (name LIKE '%张三%' AND id IN ('1', '2', '3', '4', '5') )

三. 支持后端自定义控制查询条件,使用实例:

public Page<GoodsVO> pageExample(PageQO page) {
    Map<String, String> param = new HashMap<>();
    // 创建时间在 2024-06-06 00:00:00 到 2024-06-06 23:49:22之间
    param.put("g.createTime", "bt 2024-06-06 00:00:00,2024-06-06 23:49:22");
    // 名称包含 张或李或王
    param.put("name", "lk 张 or 李 or 王");
    // 名称或简介包含 1314
    param.put("name or description", "lk 1314");
    // id等于 1
    param.put("g.id", "1");

    QueryWrapper queryWrapper = QueryUtils.buildQueryWrapperJson(param);
    return baseMapper.selectByQO(PageUtil.getPage(page), queryWrapper);
}

// 翻译SQL
/** SELECT * from goods g JOIN goods_store gs ON g.id = gs.goods_id
    WHERE
    (
        ( name LIKE '%1314%'  OR description LIKE  '%1314%' )
        AND ( name LIKE '%张%' OR name LIKE '%李%' OR name LIKE '%王%' )
        AND g.id = '1'
        AND g.create_time BETWEEN '2024-06-06 00:00:00' AND '2024-06-06 23:49:22'
    )
*/

源码地址: 基于MybatisPlus 的@Query注解使用示例

  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: MybatisPlus提供了丰富的注解支持,可以使您在SpringBoot中轻松实现代码查询。它们包括@Select、@Insert、@Update、@Delete、@SelectProvider等,可以满足您的不同需求。代码实现很简单:@Select("SELECT * FROM user WHERE id = #{id}") User findById(int id);@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})") int insert(User user);@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}") int update(User user);@Delete("DELETE FROM user WHERE id=#{id}") int delete(int id); ### 回答2: 在Spring Boot项目中使用MyBatis Plus进行注解查询可以通过以下步骤实现: 1. 添加依赖:在项目的pom.xml文件中添加MyBatis Plus的依赖。可以通过以下方式添加依赖: ``` <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>最新版本号</version> </dependency> ``` 2. 配置数据源:在项目的application.properties或application.yml文件中配置数据源相关信息,包括数据库URL、用户名、密码等。 3. 创建实体类:创建与数据库表对应的实体类,并使用MyBatis Plus的注解进行字段映射。例如,使用`@TableName`注解指定实体类和数据库表的对应关系,使用`@TableId`注解指定主键。 4. 创建Mapper接口:创建一个Mapper接口,继承MyBatis Plus提供的BaseMapper接口。不需要实现该接口中的方法,因为MyBatis Plus会根据方法名自动生成SQL语句。 5. 注解查询:在业务逻辑的代码中,通过注入Mapper对象,调用其提供的方法进行查询。例如,使用`@Select`注解指定SQL语句,使用`@Param`注解指定参数。 以下是一个示例: ```java @Entity @TableName("user") public class User { @TableId private Long id; private String username; private String password; // 省略getter和setter方法 } @Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE username = #{username}") User findByUsername(@Param("username") String username); } @Service public class UserService { @Autowired private UserMapper userMapper; public User getUserByUsername(String username) { return userMapper.findByUsername(username); } } ``` 在上面的例子中,`User`是一个实体类,使用`@TableName`注解指定与数据库表`user`的对应关系。`UserMapper`接口继承了`BaseMapper`接口,其中`findByUsername`方法使用了`@Select`注解指定查询语句,并使用了`@Param`注解指定参数。`UserService`中注入了`UserMapper`对象,并调用其方法进行查询。 ### 回答3: 使用Spring Boot和MyBatis Plus进行注解查询的步骤如下: 1. 首先,在你的Spring Boot项目中添加依赖。在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>latest-version</version> </dependency> ``` 2. 创建数据库表和实体类。在你的数据库中创建表,并创建对应的实体类。 例如,创建一个User表,包含id、name和age字段,对应的User实体类如下: ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 3. 创建Mapper接口。在你的项目中创建一个Mapper接口,并使用MyBatis Plus的注解来定义查询方法。 例如,创建一个UserMapper接口,在该接口中使用`@Select`注解进行查询: ```java @Mapper public interface UserMapper extends BaseMapper<User> { @Select("SELECT * FROM user WHERE age > #{age}") List<User> findUsersByAge(@Param("age") Integer age); } ``` 4. 使用Mapper进行查询。在你的服务类或Controller中使用自动注入的UserMapper实例进行查询。 例如,在UserController中调用查询方法: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/age/{age}") public List<User> getUsersByAge(@PathVariable Integer age) { return userMapper.findUsersByAge(age); } } ``` 现在,你可以通过发送GET请求`/users/age/18`来获取年龄大于18的用户列表。 以上就是使用Spring Boot和MyBatis Plus进行注解查询的简单示例。你可以根据具体的业务需求使用不同的注解SQL语句来查询和操作数据库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值