MyBatis OGNL Comparison Pitfall: Single Character vs String
The article reveals that MyBatis’s OGNL treats a single‑character literal like '1' as a Character, causing equality checks against String values in if tags to fail, and shows how using double quotes, toString(), or proper type conversion resolves the comparison pitfall.
This article explains a common MyBatis pitfall when using OGNL expressions for conditional comparisons. When comparing a single character digit (like '1') with a string in MyBatis's <if> conditions, the comparison fails because OGNL treats the single character as a Character type rather than a String, leading to incorrect equality checks.
The article demonstrates this issue with a practical example using a UserInfoTab object and MyBatis mapper XML. It shows that conditions like <if test="userId == '1' "> do not work as expected, while alternatives like using double quotes ("1") or toString() conversion do work correctly.
The root cause is explained through MyBatis's use of OGNL (Object-Graph Navigation Language) for expression parsing. The article references the OgnlOps.compareWithConversion method in MyBatis source code, which handles type conversion and comparison logic, explaining why Character and String comparisons fail.
Key takeaways include understanding OGNL's type handling in MyBatis, proper syntax for conditional comparisons, and debugging techniques for similar issues. The article provides both the problematic code and correct solutions with code examples.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.