《关于我用Mybatis-Plus实现模糊查询并高亮显示这档事》

前言

关于模糊查询搜索并高亮显示结果,大多都用es分布式搜索引擎进行实现,但整合es的过程比较复杂,像创建索引库、导入文档数据、同步更新DB数据,各种请求Request应接不暇。因此,在此直接用了Mybatis-Plus进行实现,并对搜索结果进行了高亮处理,虽然MP模糊搜索性能很差,但平常编码测试自己玩玩还是可以的。

具体实现

1.数据表

2.Controller层

@RestController
@RequestMapping("/course")
@Api(description = "课程接口")
public class CourseController {
    @Autowired
    private CourseService courseService;
    
    @ApiOperation("分页模糊查询所有匹配课程,并高亮显示结果")
    @PostMapping("getAll/course/highlighter/{currentPage}/{pageSize}/{name}")
    public Result getAllCourseHighLighter(@PathVariable Integer currentPage,
                                          @PathVariable Integer pageSize,
                                          @PathVariable String name) {
        return courseService.getAllCourseHighLighter(currentPage, pageSize, name);
    }
}

3.Service层

@Slf4j
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Override
    public Result getAllCourseHighLighter(Integer currentPage, Integer pageSize, String name) {
        IPage<Course> page = new Page<>(currentPage, pageSize);
        //可用MP方便地添加一系列过滤、排序条件
        lambdaQuery().like(Course::getName, name).page(page);
        long total = page.getTotal();
        List<Course> courseList = page.getRecords().stream().map(o -> {
            String originName = o.getName();
            //替换模糊查询字段值 -> 如果前端是Vue的话直接用v-html="name"展示即可高亮显示
            String newName = originName.replaceAll(name, "<span style='color: rgb(246, 93, 142)'>" + name + "</span>");
            o.setName(newName);
            return o;
        }).collect(Collectors.toList());
        return Result.ok().data(MapUtil.builder()
                .put("total", total)
                .put("courseList", courseList).build()).msg("成功分页、高亮、模糊查询所有课程");
    }

}

4.测试结果

{
  "flag": true,
  "code": 200,
  "msg": "成功分页、高亮、模糊查询所有课程",
  "data": {
    "total": 2,
    "courseList": [
      {
        "id": 1,
          //成功为搜索字段加上高亮样式
        "name": "<span style='color: rgb(246, 93, 142)'>Java</span>从入门到精通",
        "price": 1,
        "poster": "https://cn.bing.com/images/search?view=detailV2&ccid=S3ilIbGn&id=C4ABDD41B61EB8FB3575D6ADAF34DC3B283A1F0C&thid=OIP.S3ilIbGnQ2MhpsxIijA3dAHaEK&mediaurl=https%3a%2f%2fpic1.zhimg.com%2fv2-96727fec3160ad7114bd424377a90ee8_r.jpg&exph=1080&expw=1920&q=%e9%ab%98%e6%b8%85%e7%94%b5%e8%84%91%e5%8a%a8%e6%bc%ab%e5%a3%81%e7%ba%b8&simid=607994978101366522&FORM=IRPRST&ck=6F8344C168E5DD4ADE4E923F7DA58E5E&selectedIndex=7",
        "categoryId": 3,
        "teacherId": 1,
        "createTime": "2023-01-09 11:10:02",
        "updateTime": "2023-01-09 11:10:02",
        "isDeleted": 0,
        "sort": 1
      },
      {
        "id": 3,
        "name": "<span style='color: rgb(246, 93, 142)'>Java</span>从精通到面试",
        "price": 1,
        "poster": "https://cn.bing.com/images/search?view=detailV2&ccid=SCg60HrS&id=637D0A1947C6C3698F642AE12F11FC672E24C60C&thid=OIP.SCg60HrSm5lcRm0gcGlDAAHaEK&mediaurl=https%3a%2f%2fpic2.zhimg.com%2fv2-63dad01ff5c14e79d1622dc54865f5ed_r.jpg&exph=1080&expw=1920&q=%e9%ab%98%e6%b8%85%e7%94%b5%e8%84%91%e5%8a%a8%e6%bc%ab%e5%a3%81%e7%ba%b8&simid=608002438460677649&FORM=IRPRST&ck=F0EFE8FF0A26FFB2ECC6AAF24F4BE4EC&selectedIndex=10",
        "categoryId": 3,
        "teacherId": 1,
        "createTime": "2023-01-09 11:11:26",
        "updateTime": "2023-01-09 11:11:26",
        "isDeleted": 0,
        "sort": 2
      }
    ]
  }
}

5.前端展示

前端如果是Vue的话直接用v-html=name即可实现高亮展示,这里就不具体做测试了。

总结

Mybatis-Plus真香。

Mybatis-Plus是一个Mybatis的增强工具包,它简化了Mybatis的使用,并且提供了很多实用的功能,如自动生成代码、条件构造器、分页插件等。下面是Mybatis-Plus实现数据查询的步骤: 1. 创建实体类 首先需要创建一个实体类,该实体类需要与数据库中的表对应,其中成员变量需要与表中的列一一对应,可以使用注解或XML配置进行映射。例如: ```java public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; private String email; // getter和setter方法省略 } ``` 2. 配置Mapper接口 接着需要创建一个Mapper接口,该接口需要继承BaseMapper接口,这样就可以直接使用Mybatis-Plus提供的大量方法进行数据查询。例如: ```java public interface UserMapper extends BaseMapper<User> { } ``` 3. 使用Wrapper构造查询条件 接下来可以使用Wrapper对象构造查询条件,Wrapper是一个抽象类,它提供了很多静态方法,可以方便地构造各种条件。例如: ```java QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", "Tom").gt("age", 18).orderByDesc("age"); ``` 上述代码表示查询名字为Tom且年龄大于18岁的用户,并按照年龄降序排列。 4. 执行查询 最后只需要调用Mapper接口中的方法即可执行查询,例如: ```java List<User> userList = userMapper.selectList(wrapper); ``` 上述代码表示执行查询,并将结果存储在一个List中。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值