Mastering OGNL in MyBatis: Essential Expressions and Tricks
This article explains what OGNL (Object Graph Navigation Language) is, how it is used in MyBatis dynamic SQL, and provides a comprehensive guide to its conditional assertions, arithmetic assignments, built‑in methods, value retrieval, and assignment operations with practical code examples.
Preface
OGNL (Object Graph Navigation Language) is a data‑rendering technique that simplifies access to the data layer. Although it is less common today, many Chinese ORM frameworks such as MyBatis still rely on OGNL for dynamic SQL.
OGNL in MyBatis
In MyBatis mapper files you often see test attributes that contain OGNL expressions, for example:
<if test="field!='' and field!= null">
and some_col = #{field}
</if>When field is not an empty string and not null, the condition adds a query clause. The test attribute itself is an OGNL expression. MyBatis uses OGNL mainly for two purposes.
Conditional Assertions
These are the most common OGNL usages for dynamic SQL. Typical expressions include: b1 or b2 – logical OR b1 and b2 – logical AND !b1 or not b1 – negation b1 == b2 or b1 eq b2 – equality b1 != b2 or b1 neq b2 – inequality b1 lt b2 – less than b1 gt b2 – greater than b1 lte b2 – less than or equal b1 gte b2 – greater than or equal b1 in b2 – collection contains element b1 not in b2 – collection does not contain element
These expressions are often combined with the test attribute.
Arithmetic Assignment
OGNL can also be used for assignment or property enhancement. A common use is the bind tag for fuzzy searches:
<bind name="nameLike" value="'%'+ name +'%'\Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
