MybatisPlus操作符和运算值

发布于:2024-10-15 ⋅ 阅读:(80) ⋅ 点赞:(0)

好久没有更新了,这次更新一个当前端需要对运算符和运算值都需要前端传递给后端,动态拼接运算条件时的处理方法。

1、踩雷

查询年龄 >=20,其中>=前端下拉框选择,20值前端下拉框选择

1)用户表:

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL COMMENT '主键',
  `name` varchar(12)  COMMENT '用户名称',
  `hobby` varchar(12) DEFAULT NULL COMMENT '爱好',
  `age`  int(11) DEFAULT NULL COMMENT '用户年龄',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户表';

2)定义VO:

import lombok.Data;

@Data
public class UserVO extends User {

	/**
	 * 操作运算符:>=/<=/=
	 */
    private String operateStr;

}

 3)Mapper内容

    <select id="selectUsers" resultType="org.springboot.xg.vo.UserVO">
        select * from user
        <where>
            <if test="userVO.operateStr!= null and userVO.operateStr != '' and  userVO.age!= null">
                and avg_delay ${userVO.operateStr} #{userVO.age}
            </if>
        </where>
    </select>

这样写虽然接受参数没有问题,但是在进入Mapper层查询时出报错,不能识别符号。

2、调整

1)定义枚举

package org.springboot.xg.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum OperateEnum {

	// 大于等于
	GREATER_THAN_OR_EQUAL_TO(1, ">="),
	// 等于
	BE_EQUAL_TO(2, "="),
	// 小于等于
	LESS_THAN_OR_EQUAL_TO(3, "<=");

	/**
	 * 操作符对应整数值
	 */
	private final Integer operateIntValue;

	/**
	 * 条件
	 */
	private final String condition;


	/**
	 * 根据值获取条件
	 *
	 * @param value 值
	 * @return 条件
	 */
	public static String getConditionByIntValue(Integer value) {
		for (OperateEnum item : OperateEnum.values()) {
			if (item.getOperateIntValue().equals(value)) {
				return item.getCondition();
			}
		}
		return null;
	}
}


网站公告

今日签到

点亮在社区的每一天
去签到