mybatis 使用if 判断字符串

mybatis 动态sql 中if判断使用的ognl表达式,现在分3中情况说明并验证。

一、情况说明:

传入的itemCode为参数传入mybatis

<if test='itemCode != null and itemCode !=""  and itemCode =="xxx" '>

1、 单个字符的数字型字符串
例如:传入参数 itemCode=“1”
以下写法不符合判断

<if test="itemCode != null and itemCode !=''  and itemCode =='1' ">

如果想让判断符合条件,可以使用一下两种写法

<if test="itemCode != null and itemCode !=''  and itemCode =='1'.toString()">
或
<if test='itemCode != null and itemCode !=""  and itemCode =="1" '>

2、单个字符的非数字型字符串
例如:传入参数 itemCode=“z”

<if test="itemCode != null and itemCode !=''  and itemCode =='z'">

会报错 NumberFormatException,如果想让判断符合条件如下写法。

<if test="itemCode != null and itemCode !=''  and itemCode =='z'.toString()"><if test='itemCode != null and itemCode !=""  and itemCode =="z" '>

3、不是单个字符的字符串
例如:传入参数 itemCode=“张三”
不用.toString()或单引号变双引号就会符合条件

<if test="itemCode != null and itemCode !=''  and itemCode =='张三'">

二、验证代码

1.添加依赖

 <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>2.6.9</version>
        </dependency>

2.代码示例

public class TestOgnl {
    public static void main(String[] args) throws Exception {
        Map<String, Object> context = new HashMap<String, Object>();
        context.put("id", "1");
        context.put("name", "z");
        context.put("sex", "man");
        System.out.println(context);
        // 单个字符的数字型字符串
        System.out.println(getValue("id == '1'", context));// false
        System.out.println(getValue("id == '1'.toString()", context));// true
        // 单个字符的非数字型字符串
        try {
            System.out.println(getValue("name == 'z'", context));
        } catch (Exception e) {
            // 'z'不能被转成数值型,此处会抛出NumberFormatException
            e.printStackTrace();
        }
        System.out.println(getValue("name == \"z\"", context));// true
        System.out.println(getValue("name == 'z'.toString()", context));// true

        // 不是单个字符的字符串
        System.out.println(getValue("sex == 'man'", context));// true
        System.out.println(getValue("sex == \"man\"", context));// true
        System.out.println(getValue("sex == 'man'.toString()", context));// true
    }
    public static Object getValue(String expression,Object map) throws OgnlException {
        return Ognl.getValue(expression, map);
    }

}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值