mysql字段多个值,mybatis/mybatis-plus匹配查询

mysql中有一个字段是字符串类型的,category字段值有多个用逗号分割的,例如:娱乐,时尚美妆,美食 。现在想实现这么一个功能, 前端传参 字符串,美食,娱乐。现在想在mybatis的xml中实现,查询,能查到category只要包含美食或者娱乐的数据行。

数据如下示例,category字段中有多个值,country字段中只有一个值

Mybatis xml 查询如下:

XML 复制代码
 <where>
           
            <if test="sex!= null and sex!=''">
                and sex= #{sex}
            </if>
            <if test="country != null and country != ''">
                AND country IN
                <foreach item="item" index="index" collection="country.split(',')" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="category != null and category != ''">
                and
                <foreach item="item" index="index" collection="category.split(',')" open="(" separator="OR" close=")">
                    FIND_IN_SET(#{item}, category) > 0
                </foreach>
            </if>
        </where>

Mybatis-plus中实现:

java 复制代码
 QueryWrapper<对象> lqw = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(paramObj.getCountry())) {
                String[] split = paramObj.getCountry().split(",");
                List<String> countryList = Arrays.asList(split);
                lqw.in("country", countryList);
            }

           
        if (StringUtils.isNotEmpty(paramObj.getCategory())) {
            String[] split = paramObj.getCategory().split(",");

            StringBuilder sb = new StringBuilder();
            sb.append("(");
            for(int i = 0; i< split.length; i++){
                String catgory = split[i];
                if(i == split.length -1){
                    sb.append("FIND_IN_SET('" + catgory + "', category) > 0").append(")");
                }else{
                    sb.append("FIND_IN_SET('" + catgory + "', category) > 0").append(" or ");
                }

            }

            lqw.apply(sb.toString());
        }
相关推荐
记忆不曾留3 小时前
Mybatis 源码解读-SqlSession 会话源码和Executor SQL操作执行器源码
mybatis·二级缓存·sqlsession会话·executor执行器·一级缓存localcache
昵称为空C1 天前
SpringBoot 实现DataSource接口实现多租户数据源切换方案
后端·mybatis
isyangli_blog2 天前
(2-10-1)MyBatis的基础与基本使用
java·开发语言·mybatis
_码农121382 天前
Mybatis简单练习注解sql和配置文件sql+注解形式加载+配置文件加载
mybatis
期待のcode2 天前
Maven
java·spring·maven·mybatis
独泪了无痕2 天前
一文搞懂MyBatis中的TypeHandler
数据库·后端·mybatis
Easocen2 天前
Mybatis学习笔记(十)
mybatis
千睢3 天前
Mybatis实现页面增删改查
mybatis
Warren983 天前
Java后端面试题(含Dubbo、MQ、分布式、并发、算法)
java·开发语言·分布式·学习·算法·mybatis·dubbo
羊锦磊3 天前
[ Mybatis 多表关联查询 ] resultMap
java·开发语言·数据库·mysql·mybatis