MyBatis if test 判断字符串相等不生效问题
作者:长安明月 时间:2021-10-11 22:42:01
MyBatis if test 判断字符串相等不生效
采用 MyBatis 框架操作 MySQL 数据库时,判断传入的字符串 priceFlag 值为"0"时,按照 price 属性降序排列,如下 xml 语句未生效:
<if test="priceFlag != null and priceFlag == '0'">
ORDER BY price DESC
</if>
原因分析
MyBatis 是使用 OGNL 表达式来进行解析的,在 OGNL 表达式中,'0’会被解析成字符,因为 java 是强类型的,char 和 String 不等,所以 if 标签中的 SQL 不会被解析。
解决方法
解决这个问题,可以把 if test 判断语句修改成如下几种方式中的任何一种:
<if test='"0" == priceFlag'>
或者
<if test='"0".equals(priceFlag)'>
或者
<if test="'0'.toString() == priceFlag">
修改完成后,SQL 语句就可以被解析了。
MyBatis if test 判断字符串相等的坑
自己开发的系统,客户反映有问题,本着不想改java代码,想想从数据库入手,加一些判断条件就想到了if test判断等于某个字符串执行另一个sql语句的原则,没想到想当然了,使用 if test=“sex==‘m’”直接报错,看了下网上果然大家都有遇到这样的问题,解决方式如下:
1. if 判断字符串
错误写法:if test="status == 'Y'"特别是数字字符的时候。。。。
结果:抛异常NumberFormatException异常!提示内容非常少,看不出问题在哪里!
正确写法:if test='status == "y" '
还可以这样写:if test="status == 'y'.toString()"
2. if嵌套
<if test="@com.qbao.tickets.common.util.MybatisUtils@isNotEmpty(firstLetter)">
<if test="firstLetter=='-1'.toString()">
and FIRST_LETTER is null or FIRST_LETTER =''
</if>
<if test="firstLetter!='-1'.toString()">
and FIRST_LETTER = #{firstLetter, jdbcType=VARCHAR}
</if>
</if>
来源:https://blog.csdn.net/piaoranyuji/article/details/108280023
标签:MyBatis,if,test,判断,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
如何安装java的运行环境IDEA
2022-09-20 10:42:38
![](https://img.aspxhome.com/file/2023/0/64380_0s.png)
SpringBoot中发送QQ邮件功能的实现代码
2022-09-25 10:19:59
![](https://img.aspxhome.com/file/2023/8/72648_0s.png)
C#远程发送和接收数据流生成图片的方法
2021-08-31 00:30:10
Java如何根据不同系统动态获取换行符和盘分割符
2022-02-27 10:33:10
MyBatis-Plus分页插件不生效的解决方法
2023-03-10 20:24:58
![](https://img.aspxhome.com/file/2023/0/68200_0s.png)
SpringBoot2.x过后static下的静态资源无法访问的问题
2023-07-07 00:21:09
![](https://img.aspxhome.com/file/2023/3/67623_0s.jpg)
SpringBoot中如何对actuator进行关闭
2022-11-30 01:56:37
![](https://img.aspxhome.com/file/2023/9/62349_0s.png)
Java魔法堂之调用外部程序的方法
2023-11-09 07:14:16
![](https://img.aspxhome.com/file/2023/9/59209_0s.png)
C#清除WebBrowser中Cookie缓存的方法
2022-01-13 20:01:08
基于java构造方法Vector遍历元素源码分析
2023-11-25 05:21:40
使用SpringBoot自定义starter的完整步骤
2023-09-26 02:41:48
![](https://img.aspxhome.com/file/2023/8/71608_0s.png)
Winform下实现图片切换特效的方法
2023-04-20 21:26:28
java反射之通过反射了解集合泛型的本质(详解)
2023-02-04 03:10:25
![](https://img.aspxhome.com/file/2023/1/68151_0s.png)
详解C# 匿名对象(匿名类型)、var、动态类型 dynamic
2022-03-26 18:43:02
![](https://img.aspxhome.com/file/2023/8/72458_0s.png)
Android数据存储方式操作模式解析
2023-07-27 02:47:05
C#中Span相关的性能优化建议
2021-07-05 15:42:26
![](https://img.aspxhome.com/file/2023/7/69817_0s.png)
Spring Boot 中密码加密的两种方法
2021-09-12 15:08:38
![](https://img.aspxhome.com/file/2023/5/78895_0s.png)
C#从画刷创建画笔的方法
2022-11-22 15:49:17
C#中的try catch finally用法分析
2021-06-20 18:31:28
SpringAOP 如何通过JoinPoint获取参数名和值
2023-11-01 00:50:36
![](https://img.aspxhome.com/file/2023/1/69351_0s.png)